0

I'm trying to construct a set of tuples (i, v), where i is an int and v is a double. The set cannot contain two tuples with the same value of i.

To do this, I think I should use a std::set of std:tuples. Something like:

#include <tuple>
#include <set>
using namespace std;

set<tuple<int, double>> mySet;

The std::set class allows me to specify a comparator, and I think I should use this to avoid different tuples with the same value of i, but I don't know how to do it??

a06e
  • 18,594
  • 33
  • 93
  • 169

2 Answers2

3

std::tuple already provides a operator< that you can use for comparisons, but it compares all elements of the tuple. You simply need to provide a comparator that compares the first element of the tuple and ignores the second.

struct comparator
{
    bool operator()(const tuple<int, double> & lhs, const tuple<int, double> &  rhs)
    {
        return get<0>(lhs) < get<0>(rhs);
    }
};
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

A map may be a better choice std::map<int, double>. The interesting thing is that the value_type of the map is std::pair<const int, double> which can be used like a tuple : std::get ...

Kiwi
  • 2,698
  • 16
  • 15