문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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));

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top