C++,STL。从矢量中删除具体值<string>?

c++, stl. Remove a concrete value from vector<string>?

本文关键字:lt string gt 删除 STL C++      更新时间:2023-10-16

例如:

vector<string> strs;
strs.push_back("1");
strs.push_back("2");
strs.push_back("3");
strs.push_back("4");
strs.push_back("3");
//strs.removeAllOccurencesOfValue("3");

我发现了这个例子:

链路

但是有什么更简单的方法吗?例如使用boost框架?

有一个非常好的删除习惯用法:

#include <algorithm>
strs.erase( std::remove(strs.begin(), strs.end(), std::string("3")), strs.end() );

Scott Meyers在他的《有效的STL:改进标准模板库使用的50种具体方法》中谈到了"删除"习语。它似乎非常适合您的情况:

#include <algorithm>    // for std::remove
vector<string> strs;
strs.push_back("1");
strs.push_back("2");
strs.push_back("3");
strs.push_back("4");
strs.push_back("3");
strs.erase( std::remove( strs.begin(), strs.end(), "3" ), strs.end() );