대신 "수동" 선택적으로 해당 항목을 삭제 벡터의 내용을 걷고, 나는 적절하게 결합 STL의 이미 구축 된 알고리즘을 사용하는 것이 좋습니다 것입니다.
당신이 삭제-제거 관용구 사용을 고려할 수하는 std::vector
에서 몇 가지 속성을 만족하는 항목을 삭제, 특히
관용구을 지우기가-제거를 사용.
This Q&A on Stackoverflow은 std::vector
사례를 포함하여 STL 컨테이너에서 항목을 지울 수있는 몇 가지 옵션에 대해 설명합니다.
당신은 컴파일 가능한 코드 아래, live here 주석 찾을 수 있습니다
#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;
}
출력 : 또한 this very similar question on Stackoverflow
a = {the, of}
b = {oranges, the, of, apples}
After removing:
a = {}
PS
참고. std::set_difference()
다른 방법을 사용
는
, 예를 std::set_difference()
을 사용할 수있다 다음 코드와 같은 것입니다 : live here.
은 (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;
}
내부 루프의 중간에 'a [i]'의 의미가 바뀝니다. –
벡터를 정렬 할 수 있습니까? 그러면'std :: set_difference'를 사용할 수 있습니다. –
예. 아마도 그것이 작동하지 않는 이유 일 것입니다. 그런데 어떻게 문자열을 정렬 할 수 있습니까? 나는 문자열로 작업해야한다. – muqsitnawaz