总的来说,建议使用STL已经构建好的
算法,而不是手动遍历向量内容并选择性地删除其项目。
使用Erase-Remove惯用语
特别地,要从
std::vector
中删除满足某些属性的项目,可以考虑使用
erase-remove惯用语。 这个
Stackoverflow上的问答讨论了一些从STL容器(包括
std::vector
)中删除项目的选项。
您可以在下面找到有注释的可编译代码,
在线查看:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print(const char* name, const vector<string>& v);
int main()
{
vector<string> a = {"the", "of"};
vector<string> b = {"oranges", "the", "of", "apples"};
print("a", a);
print("b", b);
a.erase(
remove_if(
a.begin(),
a.end(),
[&b](const string& s)
{
auto it = find(b.begin(), b.end(), s);
return (it != b.end());
}
),
a.end()
);
cout << "\nAfter removing:\n";
print("a", a);
}
void print(const char* name, const vector<string>& v)
{
cout << name << " = {";
bool first = true;
for (const auto& s : v)
{
if (first)
{
first = false;
cout << s;
}
else
{
cout << ", " << s;
}
}
cout << "}" << endl;
}
输出:
a = {the, of}
b = {oranges, the, of, apples}
After removing:
a = {}
使用std::set_difference()
另一种方法是使用std::set_difference()
,例如以下代码:点击此处查看实时演示。
(请注意,在这种情况下,根据set_difference()
的先决条件,输入向量必须已经排序。)
PS
还要注意这个在Stackoverflow上非常相似的问题。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
void print(const char* name, const vector<string>& v);
int main()
{
vector<string> a = {"the", "of"};
vector<string> b = {"oranges", "the", "of", "apples"};
print("a", a);
print("b", b);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
vector<string> c;
set_difference(a.begin(), a.end(),
b.begin(), b.end(),
inserter(c, c.begin()));
print("difference(a,b)", c);
}
void print(const char* name, const vector<string>& v)
{
cout << name << " = {";
bool first = true;
for (const auto& s : v)
{
if (first)
{
first = false;
cout << s;
}
else
{
cout << ", " << s;
}
}
cout << "}" << endl;
}
a[i]
的含义在内部循环的中间发生了改变。 - Kerrek SBstd::set_difference
。 - Kerrek SB