我是C ++中的Vector的新手,在遵循了Vector的教程之后,我编写了如下程序:
int main()
{
vector<int> regular;
vector<int> large;
int n;
do{
cout << "Enter a number : " ;
cin >> n;
regular.push_back(n); //add the number to the vector
}while (n!=0);
for(int i = 0; i<regular.size(); i++){
// this is to test if each value is larger than x
if(largevalues(regular[i]))
{
large.push_back(regular[i]);
cout<< large[i] <<endl;
}
}
return 0;
}
但是,像这样的输入的输出1, 2, 3, 4, 5 , 6, 7
不符合预期。它将打印一些奇怪的值。
如果代替
large.push_back(regular[i]);
cout<< large[i] <<endl;
我只是做
cout<< regular[i] <<endl;
然后它将打印所有大于x的数字。有人可以解释为什么large.push_back(regular[i]);
不会将这些值添加到新向量中吗?
内容 regular[i]
不一定与..
内容large[i]
之后push_back
例如,如果“常规”的大小为10,而“大”的大小为1
然后,您将常规的第10个索引推回大并尝试访问large[10]
...您将遇到索引超出范围的问题
如果您想查看刚刚退回的商品的价值,可以说类似 cout<< large.back() <<endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句