Reputation: 425
I'm trying to remove duplicates from vector using "unique" but it does not seem to be working. This is my first time using iterators. Please advise where I'm doing wrong. Thank in advance!
Edit: Sort p2dvector, use unique and erase to find and remove duplicates. But duplicates are not removed.
Output:
X:3 and Y:2 are still duplicated.
x: 3
y: 2
x: 6
y: 4
x: 3
y: 2
vector<Point2D> p2dvector;
//vector<Point2D> :: iterator it, it_end;
void readData()
{
cout<< "Please enter filename : ";
cin >> inputFile;
fstream fileStream;
fileStream.open(inputFile.c_str(),fstream::in);
int records = 0;
while( fileStream.good() )
{
string line = "";
while (getline (fileStream, line))
{
stringstream ss (line);
getline (ss, className, ',');
if (className == "Point2D")
{
int x, y;
getline (ss, p2dX, '[');
getline (ss, p2dX, ',');
getline (ss, p2dY, ' ');
getline (ss, p2dY, ']');
istringstream (p2dX) >> x;
istringstream (p2dY) >> y;
Point2D p2d (x, y);
p2dvector.push_back(p2d);
//amended to this
sort(p2dvector.begin(), p2dvector.end());
p2dvector.erase(unique(p2dvector.begin(), p2dvector.end()), p2dvector.end());
/*
for (it = p2dvector.begin(); it < p2dvector.end(); it++)
cout << "before : " << *it;
it_end = unique(p2dvector.begin(), p2dvector.end());
for (it = p2dvector.begin(); it < it_end; it++)
cout << "removed duplicates : " << *it; */
}
}
}
}
Error: (edit: this error is resolved after using sort, unique and erase but duplicate data is not removed)
In file included from /usr/include/c++/4.6/algorithm:63:0,
from Assn3.cpp:7:
/usr/include/c++/4.6/bits/stl_algo.h: In function ‘_FIter std::unique(_FIter, _FIter) [with _FIter = __gnu_cxx::__normal_iterator<Point2D*, std::vector<Point2D> >]’:
Assn3.cpp:149:55: instantiated from here
/usr/include/c++/4.6/bits/stl_algo.h:1189:2: error: no match for ‘operator==’ in ‘__dest.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Point2D*, _Container = std::vector<Point2D>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = Point2D&]() == __first.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Point2D*, _Container = std::vector<Point2D>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = Point2D&]()’
Upvotes: 0
Views: 811
Reputation: 45470
std::unique
calls operator==
to compare elements by default. you need to define it for Point2D
bool operator==(const Point2D& lhs, const Point2D& rhs);
std::unique
removes adjacent duplicates, if you meant to remove all duplicates, you need to and sort p2dvector
.
Upvotes: 3