stl hash_map and user defined data type update

A

anjangoswami06

Hi,

I am interested to know how it is possible to update the data type with
"insert" with stl hash_map. Suppose we have,
hash_map<const char *, MyDataType, hash_compare<const char*,
some_compare_func_obj>>
x;

//I want to insert a new instance of MyDataType if a new key is
encountered but if it is a key //which already exists I want to update
the existing values of the members of MyDataType //instance which is
associated with the key.

//MyDataType may be as follows:

struct MyDataType {
int x;
int y;
char[2048] str;
MyDataType(){x=0;y=0; strcpy(str,"NONEYET"));
};

//one way of insertion is the following but I will not be able to
update already instanciated
//MyDataType in a straight manner.
x.insert(make_pair("some string",MyDataType data))

//I am trying to find a simple and elegant method for this.

I will appriciate any suggestion.

Thanks.
Buchan
 
M

mlimber

Hi,

I am interested to know how it is possible to update the data type with
"insert" with stl hash_map. Suppose we have,
hash_map<const char *, MyDataType, hash_compare<const char*,
some_compare_func_obj>>
x;

//I want to insert a new instance of MyDataType if a new key is
encountered but if it is a key //which already exists I want to update
the existing values of the members of MyDataType //instance which is
associated with the key.

//MyDataType may be as follows:

struct MyDataType {
int x;
int y;
char[2048] str;
MyDataType(){x=0;y=0; strcpy(str,"NONEYET"));
};

//one way of insertion is the following but I will not be able to
update already instanciated
//MyDataType in a straight manner.
x.insert(make_pair("some string",MyDataType data))

//I am trying to find a simple and elegant method for this.

I will appriciate any suggestion.

Although you may not know or care, your question is on-topic here
because hash_map is part of TR1 (as std::tr1::unordered_map).

Conceptually, a hash_map is a Unique Associative Container (see
http://www.sgi.com/tech/stl/UniqueAssociativeContainer.html), which
means it doesn't allow non-unique keys. If you supply a non-unique key,
hash_map::insert() doesn't replace the existing one but rather returns
an iterator to the existing key/value. Thus, to force a replacement of
an existing value, you can do this:

(*((x.insert(make_pair("some string", MyDataType()))).first)).second =
data;

where data is of MyDataType. Pretty ugly, huh? That's why they also
supply a convenience function that allows you to do the same thing like
this:

x[ "some string" ] = data;

Elegant enough!

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top