Wednesday, February 18, 2009

Working with a std::vector inside an std::map

Suppose we have a map which contains std::string keys and std::vector values, it will be defined as following

std::map<std::string,std::vector> map_str_vector;

I was doing something like this:

std::vector vec_active_channels;
vec_active_channels.push_back("Some string");

map_str_vector["Some_Key"] = vec_active_channels;

Later in the code, I was erasing an element from the vector like this:

std::vector vec_temp = map_str_vector["Some_Key"];

But you know what, later on when I examined the vector, its size won't be changed.
The reason is when I did:
std::vector vec_temp = map_str_vector["Some_Key"];

A new object of std::vector was created and placed in vec_temp, and the call
was erasing first element from the new object.

The right way to remove a std::vector from a std::map value field is given below


We can put an if statement behind this erase operation, to check whether this key exists in the map or not.

No comments:

Post a Comment

Feel free to talk back...