Reputation: 61
I'm trying to insert some pair value into a map. May map is composed by an object and a vector of another object. i don't know why but the only way to make the code to compile is to declare the first object like a pointer. But in this way when I insert some object, only the first pair is put into the map.
My map is this:
map<prmEdge,vector<prmNode> > archi;
this is the code:
{
bool prmPlanner::insert_edge(int from,int to,int h) {
prmEdge e;
int f=from;
int t=to;
if(to<from){
f=to;
t=from;
}
e.setFrom(f);
e.setTo(t);
vector<prmNode> app;
prmNode par=nodes[e.getFrom()];
prmNode arr=nodes[e.getTo()];
app.push_back(par);
app.push_back(arr);
archi.insert(pair<prmEdge,vector<prmNode> >(e,app) );
return true;
}
}
In this way, I have an error in compilation in the class pair.h. What could I do?? Thank you very much.
Upvotes: 0
Views: 497
Reputation: 20031
The class prmEdge
needs to define a comparison function (default is operator<
) to work with std::map
. Although you don't post that code, I would expect that to be your problem (for the record, pointer have an operator<
defined.
struct A {
int a;
bool operator<(A other)
{
return a < other.a;
}
};
struct B {
int b;
};
bool cmp(B lhs, B rhs)
{
return lhs.b < rhs.b;
}
std::map<A, int> map_a;
std::map<B, int, std::pointer_to_binary_function<B, B, bool> > map_b(std::ptr_fun(cmp));
Upvotes: 1
Reputation: 19327
Map elements are ordered by their keys. But the map needs to know how:
Either overload the <
operator in the prmEdge class...
class prmEdge
{
//...
public:
bool operator<(const prmEdge& right) const
{
//...
}
};
...or specify a comparator for the map:
class Comparator
{
public:
bool operator()(const prmEdge& left, const prmEdge& right) const
{
// ...
}
};
map<prmEdge, vector<prmNode>, Comparator> archi;
Upvotes: 0
Reputation: 57535
You need to supply a comparator for prmEdge. My guess is that it uses the default comparator for map, e.g. comparing the address of the key -- which is always the same because e
is local.
Objects that serve as Keys in the map need to be ordered, so you either need to supply a operator for comparing edges, or a comparator function for map.
class EdgeComparator {
public:
bool operator( )( const prmEdge& emp1, const prmEdge& emp2) const {
// ... ?
}
};
map<prmEdge,vector<prmNode>, EdgeComparator > archi;
The really hard part is deciding how to compare the edges so a definitive order is defined. Assuming that you only have from
and to
You can try with:
class EdgeComparator {
public:
bool operator( )( const prmEdge& emp1, const prmEdge& emp2) const {
if ( emp1.from != emp2.from )
return ( emp1.from < emp2.from );
return ( emp1.to < emp2.to );
}
};
It will sort on primary key from
and secondary to
.
Upvotes: 1