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;
}
a source to share
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.
a source to share
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
a source to share