检查向量项并添加到 C++ 中的新向量
Check vector items and add to a new vector in C++
我是 C++ 中向量的新手,在学习了有关向量的教程后,我编写了如下程序:
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
这样的输入的输出并不像预期的那样。它会打印一些奇怪的值。
if 而不是
large.push_back(regular[i]);
cout<< large[i] <<endl;
我就是这样
cout<< regular[i] <<endl;
然后它将打印所有大于 x 的数字。有人可以解释为什么 large.push_back(regular[i]);
不将这些值添加到新向量中吗?
regular[i]
的内容
不一定等同于..
push_back
之后large[i]
的内容
例如,如果常规尺码为 10,大号尺码为 1
然后,您将 regular 的第 10 个索引推回 large 并尝试访问 large[10]
...您将遇到索引越界问题
如果您想查看刚刚推回的内容的价值,您可以说 cout<< large.back() <<endl;
您似乎在最后一个循环中对 large 和 regular 使用了相同的索引。尝试:
int j = 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[j++] <<endl;
}
}
我是 C++ 中向量的新手,在学习了有关向量的教程后,我编写了如下程序:
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
这样的输入的输出并不像预期的那样。它会打印一些奇怪的值。
if 而不是
large.push_back(regular[i]);
cout<< large[i] <<endl;
我就是这样
cout<< regular[i] <<endl;
然后它将打印所有大于 x 的数字。有人可以解释为什么 large.push_back(regular[i]);
不将这些值添加到新向量中吗?
regular[i]
不一定等同于..
push_back
large[i]
的内容
例如,如果常规尺码为 10,大号尺码为 1
然后,您将 regular 的第 10 个索引推回 large 并尝试访问 large[10]
...您将遇到索引越界问题
如果您想查看刚刚推回的内容的价值,您可以说 cout<< large.back() <<endl;
您似乎在最后一个循环中对 large 和 regular 使用了相同的索引。尝试:
int j = 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[j++] <<endl;
}
}