Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > Re: Map to stor...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 6 of 8 Topic 45803 of 47031
Post > Topic >>

Re: Map to store 3 items

by Paavo Helde <nobody@[EMAIL PROTECTED] > May 8, 2008 at 12:03 AM

Brad <brad@[EMAIL PROTECTED]
> wrote in news:fvtks8$jte$1@[EMAIL PROTECTED]
> New to C++. Just ran into a need to store three things in a map. Before 
> trying it, I thought I'd post here and ask for advice. Here is an 
> example of what I need to store:
> 
> map<string name, string prefix, int length>
> 
> Both name and prefix would be unique for each map entry. 

It's not clear what constitutes your map key and what is in your map 
value.  In general, both can be structs or cl*****. If you use a struct 
or class as the map key you have to define operator<() for it, otherwise 
the map could not maintain the keys in sorted order. E.g.

struct MyKeyType {
	std::string name_;
    	std::string prefix_;
    	MyKeyType(const std::string& name, const std::string& prefix)
    	    	: name_(name), prefix_(prefix) 
    	{}
	bool operator<(const MyKeyType& b) const {
    	    	return name_<b.name_ || (name_==b.name_ && prefix_<b.prefix_);
    	}
};

std::map<MyKeyType, int> my_map;

my_map[MyKeyType("foo","bar")] = 22;
std::string prefix1 = my_map.begin()->first.prefix_;

The same can be accomplished by using std::pair, but then you cannot give 
meaningful names to the struct members, and combining more data to the 
key becomes ***bersome.

hth
Paavo
 




 8 Posts in Topic:
Map to store 3 items
Brad <brad@[EMAIL PROT  2008-05-07 21:26:03 
Re: Map to store 3 items
"Alf P. Steinbach&qu  2008-05-08 04:02:24 
Re: Map to store 3 items
Jerry Coffin <jcoffin@  2008-05-07 22:36:57 
Re: Map to store 3 items
Juha Nieminen <nospam@  2008-05-08 10:44:14 
Re: Map to store 3 items
Jerry Coffin <jcoffin@  2008-05-08 19:07:21 
Re: Map to store 3 items
Paavo Helde <nobody@[E  2008-05-08 00:03:55 
Re: Map to store 3 items
James Kanze <james.kan  2008-05-09 05:37:52 
Re: Map to store 3 items
=?utf-8?Q?David_C=C3=B4me  2008-05-08 10:34:26 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Jul 25 15:43:27 CDT 2008.