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

后端 未结 2 1358
北恋
北恋 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: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);
    }
    

提交回复
热议问题