Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in vector of structure c++

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&)'|


possible Solution

#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;
}
like image 484
Hani Goc Avatar asked Sep 12 '14 15:09

Hani Goc


People also ask

How do I remove duplicates in vector?

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.

How do you find duplicates in vector?

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 .

Are duplicates allowed in vector?

Yes, but sorting a vector modifies the original content.


1 Answers

vector::erase() does not take a predicate. And your predicate to std::unique should check for equality.

like image 58
Nim Avatar answered Oct 02 '22 16:10

Nim