В общем, вместо обхода содержимого вектора "вручную" и выборочного удаления его элементов, я бы предложил использовать уже встроенные в STL алгоритмы, комбинируя их должным образом.
Использование идиомы "стереть-удалить"
В частности, чтобы стереть элементы, удовлетворяющие некоторому свойству, из std::vector
, вы можете рассмотреть возможность использования идиомы erase-remove.
В этом разделе вопросов и ответов на Stackoverflow обсуждаются некоторые варианты удаления элементов из контейнеров STL, включая случай std::vector
.
Вы можете найти компилируемый код с комментариями ниже, здесь:
#include <algorithm> // for std::remove_if()
#include <iostream> // for std::cout, std::endl
#include <string> // for std::string
#include <vector> // for std::vector
using namespace std;
void print(const char* name, const vector<string>& v);
int main()
{
// Input vectors
vector<string> a = {"the", "of"};
vector<string> b = {"oranges", "the", "of", "apples"};
print("a", a);
print("b", b);
// Use the erase-remove idiom
a.erase(
remove_if(
a.begin(),
a.end(),
// This lambda returns true if current string 's'
// (from vector 'a') is in vector 'b'.
[&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 = {}
PS
Обратите также внимание на очень похожий вопрос о Stackoverflow.
Используя std::set_difference()
Альтернативным подходом может быть использование std::set_difference()
, например что-то вроде следующего кода: здесь.
(Обратите внимание, что в этом случае, согласно set_difference()
предпосылке, входные векторы должны быть уже отсортированы.)
#include <algorithm> // for std::set_difference(), std::sort()
#include <iostream> // for std::cout, std::endl
#include <iterator> // for std::inserter
#include <string> // for std::string
#include <vector> // for std::vector
using namespace std;
void print(const char* name, const vector<string>& v);
int main()
{
// Input vectors
vector<string> a = {"the", "of"};
vector<string> b = {"oranges", "the", "of", "apples"};
print("a", a);
print("b", b);
// Sort the vectors before calling std::set_difference().
sort(a.begin(), a.end());
sort(b.begin(), b.end());
// Resulting difference vector
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;
}
person
Mr.C64
schedule
30.11.2014
a[i]
меняется в середине вашего внутреннего цикла. - person Kerrek SB   schedule 01.12.2014std::set_difference
. - person Kerrek SB   schedule 01.12.2014