我正在尝试使用“unique”从vector中删除重复项,但它似乎不起作用。 这是我第一次使用迭代器。请告诉我哪里做错了。 提前谢谢!
编辑: 对p2dvector进行排序,使用unique和erase来查找和删除重复项。但是没有删除重复项。
输出:
X:3和Y:2仍然是重复的。
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; */
}
}
}
}
错误:(编辑:使用排序,唯一和擦除后解决此错误,但不删除重复数据)
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&]()’
答案 0 :(得分:3)
std::unique
调用operator==
来比较元素。您需要为Point2D
bool operator==(const Point2D& lhs, const Point2D& rhs);
std::unique
删除相邻的重复项,如果您要删除所有重复项,则需要对p2dvector
进行排序。