简体   繁体   English

删除向量 STL 中最后一次出现的元素

[英]Remove last occurrence of an element in a vector STL

How can I remove only the last occurrence of a value in a C++ vector?如何仅删除 C++ 向量中最后一次出现的值?

I have this pice of code.我有这个代码。

if(vect.erase(std::remove(vect.begin(), vect.end(), oldVal),vect.end()) == vect.end()){
                cont++;                     
            }                               
            vect.push_back(newVal);

It removes all instances of a value in the array.它删除数组中某个值的所有实例。 I need it to remove only the last specific element in the vector.我需要它只删除向量中的最后一个特定元素。

Example Vector: 1 3 4 5 3 5 3 8 3 6示例向量:1 3 4 5 3 5 3 8 3 6

End I want to remove a '3' then should get:最后我想删除一个'3'然后应该得到:

1 3 4 5 3 5 3 8 6 1 3 4 5 3 5 3 8 6

Is there any canonical solution or should I try a stack os list?是否有任何规范的解决方案,或者我应该尝试堆栈操作系统列表?

  1. std::find will find an element std::find会找到一个元素
  2. std::reverse_iterator , accessed by myVector.rbegin() allows you to search from the back.myVector.rbegin()访问的std::reverse_iterator允许您从后面搜索。
  3. erase() as above. erase()如上。

Something like:就像是:

auto foundIt = std::find(vect.rbegin(), vect.rend(), oldVal);
// Find first from the back, i.e. last
if (foundIt != vect.rend()) { // if it was found
    // get back to the right iterator
    auto toRemove = --(foundIt.base());
    // and erase it
    vect.erase(toRemove);
}

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

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