つまり、必要なアルゴリズムは次のようになります。
- コンテナを逆方向に繰り返す
- 新しい鍵に遭遇した場合は、要素を離れ、
- 既に持っているキーに遭遇した場合は、その要素を削除してください。
コードで:
#include <vector>
#include <iostream>
#include <algorithm>
struct S { int key; int value; };
int main() {
std::vector<S> vec{ {0, 1}, {0, 2}, {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2} };
auto lastKey = std::numeric_limits<int>::max();
auto rLast = std::remove_if(vec.rbegin(), vec.rend(), [&lastKey](S const& s) -> bool {
if (s.key == lastKey) return true;
lastKey = s.key;
return false;
});
vec.erase(begin(vec),rLast.base());
for (auto& s : vec) {
std::cout << '{' << s.key << ',' << s.value << '}';
}
}
またはstd::unique
、他の回答で推奨されているように使用します。
auto rLast = std::unique(vec.rbegin(), vec.rend() [](S const& s1, S const& s2) {
return s1.key == s2.key;
});
vec.erase(vec.begin(), rLast.base());