简体   繁体   English

std ::移除指定元素的向量

[英]std::remove vector for specified element

I'm trying to remove a specific value that is defined by an if statement, then stores as an int, i want to then look through the vector and erase it by using 我正在尝试删除由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());
 }

but im getting these errors and i dont know why if you could help 但即时通讯收到这些错误,我不知道为什么能帮助您

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

I'm very new to c++. 我是C ++的新手。 Thanks for your help. 谢谢你的帮助。

You can simply call std::vector::erase() to remove specified element from the container: 您可以简单地调用std::vector::erase()从容器中删除指定的元素:

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

Also, just a side note, vector.erase() returns an iterator that points the next element in the vector. 另外,仅需注意,vector.erase()返回一个迭代器,该迭代器指向向量中的下一个元素。 So if you are traversing your vector through an iterator, you gotta make sure you don't loose track of the iterator after you delete an element in the vector. 因此,如果要通过迭代器遍历向量,则必须确保在删除向量中的元素后不要失去对迭代器的跟踪。

You don't really provide enough information on what you are trying to achieve. 您实际上没有提供足够的信息以了解您要实现的目标。 I suppose that i and j are loop indices? 我想ij是循环索引吗?

The "idiomatic" way of doing it is called remove/erase idiom: 做到这一点的“惯用方式”称为删除/擦除惯用语:

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

It has to be refined depending on what exactly is your use-case. 必须根据您的用例确切地对其进行完善。 Ideally the loop on j should not be a raw loop as well. 理想情况下,j上的循环也不应该是原始循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM