How do I remove the first occurrence of a value from a vector?

后端 未结 2 1347
北恋
北恋 2020-12-20 15:46

I\'m trying to get a single element from a vector and push it to the back of the vector then remove it so I won\'t have an empty section in memory. The erase-remove idiom ca

相关标签:
2条回答
  • 2020-12-20 16:13

    Find it first, then erase it:

    auto it = std::find(v.begin(),v.end(),3);
    // check that there actually is a 3 in our vector
    if (it != v.end()) {
      v.erase(it);
    }
    
    0 讨论(0)
  • 2020-12-20 16:16

    If you don't care about maintaining the ordering of the elements in the vector, you can avoid the copy of the "tail" of remaining elements on erase:

    auto it = std::find(v.begin(), v.end(), 3);
    if (it != v.end()) {
      std::iter_swap(it, v.end() - 1);
      v.erase(v.end() - 1);
    }
    
    0 讨论(0)
提交回复
热议问题