std :: remove指定元素的向量

时间:2014-04-25 16:07:12

标签: c++ vector

我正在尝试删除由if语句定义的特定值,然后存储为int,我想查看向量并使用

擦除它
if (comparedValuesBetween2[i] == First0ValueFor0Number2[j])
{
    //make sure if there are no values to compare left just leave the the while loop by editing the count.
    comparedValuesBetween2.resize(std::remove(comparedValuesBetween2.begin(), comparedValuesBetween2.end(), 8) - comparedValuesBetween2.begin());
 }

但我得到这些错误,我不知道为什么你可以帮助

  

6 IntelliSense: too many arguments in function call g:\08227 acw\ACW\Sudoku\Sudoku\main.cpp 225

     

5 IntelliSense: no suitable conversion function from "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>" to "const char *" exists g:\08227 acw\ACW\Sudoku\Sudoku\main.cpp 225

我对c ++很新。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

您只需调用std::vector::erase()即可从容器中删除指定的元素:

if (comparedValuesBetween2[i] == First0ValueFor0Number2[j])
    comparedValuesBetween2.erase(comparedValuesBetween2.begin() + i);

答案 1 :(得分:0)

另外,只是旁注,vector.erase()返回一个迭代器,指向向量中的下一个元素。因此,如果您通过迭代器遍历向量,则必须确保在删除向量中的元素后不要忽略迭代器。

答案 2 :(得分:0)

您并未真正提供有关您要实现的目标的足够信息。我想ij是循环索引?

&#34;惯用&#34;这样做的方法叫做删除/擦除习语:

for(int j; .....) {
   ... 
   if(....) {
      comparedValuesBetween2.erase(std::remove(comparedValuesBetween2.begin(), comparedValuesBetween2.end(), First0ValueFor0Number2[j]));
   }
}

必须根据您的用例确切进行细化。理想情况下,j上的循环也不应该是原始循环。

相关问题