Re: STL map with key as a structure compare function issue
<addy.varma@gmail.com> wrote in message
news:1146743040.337247.255930@v46g2000cwv.googlegroups.com...
: hi am facin a small problm,tried solving it, but my soln doesn't work.
: cud u help me out.?
:
: I need to maintain a map of <unsigned int[2], vector<int>>
:
: here's wht i did - defined a class for storing the unsigned int [2] &
: defined the corrspndng
: compare function, the problem is that inspite of filling in the map
: correctly, the find() returns an end - seems like the comparision
: function's incorrect - but I can't seem to use a
: workarnd.
:
: If nothng works then I'd have to use a double as a key - but is there a
: way out? I searched the net - but cudn't find an approp answer.
:
: thanks a bunch!
: here's the code
:
: #include <map>
: #include<string>
: #include<vector>
: # include<iostream.h>
NB: the standard header is called <iostream>
: using namespace std;
:
: class Keysq
: {
: public :
: bool operator() (const Keysq &a, const Keysq &b) const
This should not be a member function:
friend bool operator( const Keysq &a, const Keysq &b)
: {
: return a.key[0] < b.key[0];
: }
But such a comparison function does not belong within the value
class itself. It should be a distinct 'predicate' class.
If you want to implement comparision within the class itself,
you should implement operator <(a,b) instead of operator(a,b) --
then you do not need to specify a comparision object for the map.
: unsigned int key[2];
: /*ostream& operator<< (ostream& os, const Keysq& s)
: {
: return os<<s.key[1];
: }*/
:
: };
:
: typedef vector <int> df;
:
: typedef map<Keysq,df,Keysq >assocMap;
: assocMap::iterator itr;
: main()
NB: return type needs to be specified: int main()
: {
: Keysq k,a;
: k.key[0] = 10; k.key[1] = 20;
: a.key[0] = 123; a.key[1] = 32;
:
: df d;
: d.push_back(1);
: d.push_back(2);
: d.push_back(3);
:
: assocMap s ;
: s[k] = d;
: d.clear();
: d.push_back(4);
: d.push_back(5);
: d.push_back(6);
:
: s[a] = d;
: itr = s.find(k);
: cout << (itr == s.end())<<endl; // return a true!! l
Well, in spite of your errors, this should actually work
(and return 0).
: }
Also, have you considered replacing Keysq with std::pair<int,int> ?
hth - Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form