1

I'm new to C++ and I need to use Set from the STL but I'm struggling with the concept.

I have an array like this int my_data[3]

I want to create (don't know if this is possible) a set with space for 3 ints and that the key for the set would be the int that is stored on the first column.

I also want to make a custom sort.

This is what I've tried but with no success.

struct sort_set {
    bool operator() (const int& a, const int& b) const {
        int* arr1 = (int*) a;
        int* arr2 = (int*) b;
        int diff = arr2[1] - arr1[1];
        if (diff) {
            return true;
        } else if (diff == 0) {
            int diff2 = arr2[2] - arr1[2];
            if (diff2) {
                return false;
            }

        }
        return arr1[0] < arr2[0];
    }
};

set<int[3],sort_set> data;

Can someone point me in the right direction?

manlio
  • 18,345
  • 14
  • 76
  • 126
Favolas
  • 6,963
  • 29
  • 75
  • 127
  • Your `sort_set` is not a strict weak ordering. For example, with `a = {0,1,0}` and `b = {0,2,0}`, you have both `sort_set()(a,b)` and `sort_set()(b,a)` are true. – aschepler Mar 24 '14 at 13:49

1 Answers1

3

You cannot have arrays as elements of containers. They're not assignable nor copyable.

Use std::array<int, 3> if you have C++11 avaliable, or define a custom class otherwise.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • Thanks. And if I create a class with 3 int, how can I define witch one is the set key? – Favolas Mar 24 '14 at 14:12
  • You write a custom comparator (as you did above) and compare the one you want. – jrok Mar 24 '14 at 14:16
  • You access the elements through iterators. But to get an iterator, you often use a search, which uses the comparator too. – jrok Mar 24 '14 at 14:42