이 제거/삭제 관용구에 적용 할 수있는 좋은 장소입니다 : 보너스로
accDetails.erase(
std::remove_if(
accDetails.begin(), accDetails.end(),
[username](AccDetails const &a) { return username == a.username; }),
accDetails.end());
을,이 조금 더 빨리 무슨 일을했다 (또는 어쩌면 아주 조금보다 더 빨리 될 가능성이 높습니다, 벡터가 큰 경우). 각 항목을 개별적으로 지우는 것은 O (N)로 끝나지 만 N이 커지면 O (N)이됩니다.
당신이 C++ (11)를 사용할 수없는 경우 별도로 그 비교 인코딩해야하므로, 람다가 작동하지 않습니다 : 또는
class by_username {
std::string u;
public:
by_username(std::string const &u) : u(u) {}
bool operator()(AccDetails const &a) {
return u == a.username;
}
};
accDetails.erase(
std::remove_if(accDetails.begin(), accDetails.end(), by_username(username)),
accDetails.end());
을 당신이 당신의 AccDetails
클래스 operator==
를 오버로드 할 수 있습니다, , 비교를 처리합니다. 예를 들면 다음과 같습니다.
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
class AccDetail {
std::string name;
int other_stuff;
public:
AccDetail(std::string const &a, int b) : name(a), other_stuff(b) {}
bool operator==(std::string const &b) {
return name == b;
}
friend std::ostream &operator<<(std::ostream &os, AccDetail const &a) {
return os << a.name << ", " << a.other_stuff;
}
};
int main(){
std::vector<AccDetail> ad = { {"Jerry", 1}, { "Joe", 2 }, { "Bill", 3 } };
std::cout << "Before Erase:\n";
std::copy(ad.begin(), ad.end(), std::ostream_iterator<AccDetail>(std::cout, "\n"));
ad.erase(
std::remove(ad.begin(), ad.end(), "Joe"),
ad.end());
std::cout << "\nAfter Erasing Joe:\n";
std::copy(ad.begin(), ad.end(), std::ostream_iterator<AccDetail>(std::cout, "\n"));
}
중복 가능성 (http://stackoverflow.com/questions/8628951/remove-elements-of-a-vector-inside-the-loop) – Borgleader