简体   繁体   中英

inserting unique elements from std::vector to std::set

I have a class called Point , used to store x and y double values. I have a std::vector of Point s that contain duplicate values. I am trying to count the number of unique items in this vector.

I thought since std::set only unique objects, creating a set from vector would give me unique values. But I am not getting the right results. I have overloaded the equality operator. But still the duplicate values gets inserted into the set .

the current results are like below..

10,10 repetitions - 1
10,10 repetitions - 1
20,20 repetitions - 1
20,20 repetitions - 1

I am expecting...

10,10 repetitions - 2
20,20 repetitions - 2

Any clues where I am wrong? Complete code is below.

Point.h file

#ifndef POINT_H
#define POINT_H
class Point
{
public:
    Point(double x, double y);
    double getX();
    double getY();

    Point(const Point &other);

    bool operator == (const Point& p );
    bool operator != (const Point& p );

private:
    double _x;
    double _y;
};
#endif // POINT_H

Point.cpp file

#include "point.h"

Point::Point(double x, double y)
{
    _x = x;
    _y = y;
}

Point::Point(const Point &other)
{
    _x = other._x;
    _y = other._y;
}

double Point::getX()
{
    return _x;
}

double Point::getY()
{
    return _y;
}

bool Point::operator == ( const Point& p )
{
    return ( (_x  == p._x ) && (_y == p._y));
}

bool Point::operator != ( const Point& p )
{
    return !((*this) == p );
}

main.cpp file

#include <iostream>
#include <vector>
#include <set>
#include "Point.h"
using namespace std;

int main()
{
    std::vector <Point*> pointsVector;
    pointsVector.push_back(new Point(10,10));
    pointsVector.push_back(new Point(10,10));
    pointsVector.push_back(new Point(20,20));
    pointsVector.push_back(new Point(20,20));


    std::set<Point*> uniqueSet( pointsVector.begin(), pointsVector.end() );

    std::set<Point*>::iterator it;
    for (it = uniqueSet.begin(); it != uniqueSet.end(); ++it)
    {
        Point* f = *it; // Note the "*" here
        int result = std::count( pointsVector.begin(), pointsVector.end(), f );
        cout << f->getX() << "," << f->getY() << " repetitions - " << result << endl;
    }

    return 0;
}

All your elements are different because you:

1) use pointers, so you'll have to pass a custom comparator that compares pointers to Point taking into account what they point to.

2) assume std::set uses operator == or operator != when in fact it uses operator < .

I would have a collection of Point instead of Point* . Do you have any reason to use pointers instead of objects? If not, then use objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM