C++ vector<int> :将 int 元素添加到 vector 中偶数且已经在 vector 中

C++ vector<int> : add int elements to vector that are even and already in the vector

我有一个包含 6 个整数值的向量:

vector<int> my_vec = {1,2,3,4,5,6}

我想将偶数添加到向量中。我已经试过了,但不明白结果。也许有人可以为我指出正确的方向!

// Example program
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v ={1,2,3,4,5,6};

    for(int i = 0; i < v.size(); ++i){

        if(v.at(i) % 2 == 0){

            v.push_back(i);
        }
        cout << v.at(i);
    }
}

我不明白为什么将值 1、3、5 添加到向量而不是 2、4、6。

v.push_back(i);

您添加的新项目是偶数值的索引,而不是数值本身。

值为 2、4 和 6 的项目位于索引 1、3 和 5。

我猜你的意思是:

v.push_back(v.at(i));

…但是现在你的程序将永远不会结束,因为你 (a) 循环直到到达向量的末尾,并且 (b) 一直扩展向量。

您可以通过将 v.size() 的 "initial" 值存储在变量 n 中并循环直到 i 达到 n.[=17 来解决这个问题=]