std::删除指定元素的矢量

std::remove vector for specified element

本文关键字:元素 删除 std      更新时间:2023-10-16

我试图删除一个由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:8227 acwACWSudokuSudokumain.cpp 225

5 IntelliSense: no suitable conversion function from "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>" to "const char *" exists g:8227 acwACWSudokuSudokumain.cpp 225

我对c++很陌生。谢谢你的帮助。

您可以简单地调用std::vector::erase()从容器中删除指定的元素:

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

此外,vector.esers()只是一个旁注,它返回一个迭代器,指向向量中的下一个元素。因此,如果您正在通过迭代器遍历向量,则必须确保在删除向量中的元素后不会丢失对迭代器的跟踪。

您并没有真正提供足够的信息来说明您想要实现的目标。我假设ij是循环索引?

做这件事的"惯用"方式被称为删除/擦除习惯用法:

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

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