Can a vector be used as an index in a map structure in C ++?

I tried to do something like this, but it doesn't compile:

class point
{
    public:
        int x;
        int y;
};



int main()
{

    vector<point> vp1;
    vector<point> vp2;
    vector<point> vp3;

    map < vector<point>, int > m;

    m[vp1] = 1;
    m[vp2] = 2;
    m[vp3] = 3;

    map < vector<point>, int >::iterator it;
    for (it=m.begin(); it!=m.end(); it++)
    {
        cout<<m[it->first]<<endl;
    }
    return 0;
}

      

+2


a source to share


5 answers


You can use anything as an index type in std::map

, if it supports operator<

(which could define as a stand-alone function), shouldn't be a member function as long as you can write a < b

for a

and b

instances of your type of interest) using normal semantics (anti-reflective, transitive, ...). Or you can pass a binary function with the same semantics to be used instead <

, if that suits you.



+6


a source


You can, but the type used as a key in the map must be comparable, either using operator<

or using the compare / functor function you provide as the third template parameter for the map type.



+4


a source


Yes, you can. Vectors, like all containers, are comparable. The resulting map

sorts the vectors in lexicographic order.

The problem is that it is point

not comparable. You must define the sort order for points

, and then that in turn determines the lexicographic order over vector<point>

.

class point
{
    public:
        int x;
        int y;
};

bool operator<( point const &l, point const &r ) {
    return l.x < r.x? true
         : r.x < l.x? false
         : l.y < r.y;
}

      

An easier solution is to use std::pair

instead of defining your own point

.

typedef pair< int, int > point; // point::first = x, point::second = y
   // pair is already comparable; order defined as in previous example
typedef vector<point> pointvec; // OK

      

+1


a source


You haven't defined a function to compare vector<point>

Maps make requiremets for equivalence and comparison keys.

0


a source


You must declare operator<

. It will look like this (note that the three vectors in your example code look the same):

bool operator<(const vector<point>& left, const vector<point>& right)
{
    return left.size() < right.size();
}

      

-1


a source







All Articles