未能将集合的元素插入到c++中的向量中

Fail to insert the element of the set to the vector in c++

本文关键字:向量 c++ 插入 元素 集合      更新时间:2023-10-16

给定一组整数:

set<int> setA = {1,2,3,4,5};

现在我想把整数插入到某个条件下的整数向量中:

vector<int> vectorB;
for (set<int>::iterator it = setA.begin(); it != setB.end(); it++){
  if (*it % 2 == 0){
  }else{
    vectorB.insert((*it));
    count += 1;
  }
}

但我有一个错误:

error: no matching function for call to 'std::vector<int>::insert(const int&)'

为什么?

正如其他人在评论中提到的,在这种情况下不应该使用insert,而应该使用push_back

vectorB.push_back(*it);

如果存在要插入新元素的特定位置,则通常使用insert。如果您对将元素添加到特定位置不感兴趣,则可以使用push_back(顾名思义)将该元素添加到向量的末尾。