Han*_*Goc 3 c++ structure vector unique duplicate-removal
我有以下结构.我想将结构存储在矢量中.其次我想删除(context)上的重复值.我究竟做错了什么?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//Structure
struct contextElement
{
string context;
float x;
};
int main()
{
vector<contextElement> v1;
v1.push_back({"1",1.0});
v1.push_back({"2",2.0});
v1.push_back({"1",1.0});
v1.push_back({"1",1.0});
//ERROR here
auto comp = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context == rhs.context;};
//Remove elements that have the same context
v1.erase(std::unique(v1.begin(), v1.end(),comp));
for(size_t i = 0; i < v1.size();i++)
{
cout << v1[i].context <<" ";
}
cout << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:
main.cpp | 23 |错误:没有匹配函数来调用'std :: vector :: erase(__ gnu_cxx :: __ normal_iterator>,std :: vector :: iterator,main():: __ lambda0&)'|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//Structure
struct contextElement
{
string context;
float x;
};
int main()
{
vector<contextElement> v1;
v1.push_back({"1",1.0});
v1.push_back({"2",2.0});
v1.push_back({"1",1.0});
v1.push_back({"1",1.0});
//sort elements@HaniGoc: unique only removes consecutive duplicates. If you want to move all //duplicates, then either sort it first, or do something more complicated. – Mike Seymour
auto comp = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context < rhs.context;};
sort(v1.begin(), v1.end(),comp);
auto comp1 = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context == rhs.context;};
auto last = std::unique(v1.begin(), v1.end(),comp1);
v1.erase(last, v1.end());
for(size_t i = 0; i < v1.size();i++)
{
cout << v1[i].context <<" ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)