I have the following structure. I want to store the structure in a vector. Second i want to remove duplicate values on (context
). What am I doing wrong?
#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;
}
Error:
main.cpp|23|error: no matching function for call to '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;
}
Using std::remove function A simple solution is to iterate the vector, and for each element, we delete all its duplicates from the vector if present. We can either write our own routine for this or use the std::remove algorithm that makes our code elegant. This approach takes constant space but runs in O(n2) time.
1. Using std::set_difference. To find duplicates present in a vector, we can find the set difference between the original elements and the distinct elements. The following code example demonstrates this using the standard algorithm std::set_difference .
Yes, but sorting a vector modifies the original content.
vector::erase()
does not take a predicate. And your predicate to std::unique
should check for equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With