MCP
MCP

Reputation: 4536

C++ map<string, vector<char> > access

I've created a map of vectors that looks like this:

map<string, vector<char> > myMap;
string key = "myKey";
vector<char> myVector;
myMap[key] = myVector;

I want to be able to append 'char's' to the vector in the map but I can't figure out how to access said vector to append once the particular key/value(vector) has been created. Any suggestions? I'm iterating over char's and might be adding a lot to the vector as I go so it would be nice to have a simple way to do it. Thanks.


I would like the vector in map to be appended as I go. I don't need the original vector...I just need to return the map of key/vector's that I've created (after apending) so that I can pass it to another function. What does the * in map* > do? Is that refrencing a pointer? (I haven't gotten there in lecture yet) Also, do I need: myMap[key]->push_back('s'); or myMap[key].push_back('s'); ??

Upvotes: 13

Views: 67013

Answers (4)

Meysam
Meysam

Reputation: 18127

Given you know the key:

string key = "something";
char ch = 'a'; // the character you want to append

map<string, vector<char> >::iterator itr = myMap.find(key);
if(itr != myMap.end())
{
    vector<char> &v = itr->second;
    v.push_back(ch);
}

you could also use the map::operator[] to access the map entry, but if the key does not exist, a new entry with that key will be created:

vector<char> &v = myMap[key]; // a map entry will be created if key does not exist
v.push_back(ch);

or simply:

myMap[key].push_back(ch);

Upvotes: 6

Fred Foo
Fred Foo

Reputation: 363547

To append:

myMap[key].push_back('c');

Or use myMap.find, but then you have to check whether you get an end iterator. operator[] returns a reference to the vector.

But this modifies the vector stored in the map, not the original one, since you've stored a copy in the map with myMap[key] = myVector;. If that's not what you want, you should rethink your design and maybe store (smart) pointers to vectors in your map.

Upvotes: 17

Mir Milad Hosseiny
Mir Milad Hosseiny

Reputation: 2857

I have an new suggestion. You can use vector<char>* instead of vector<char> in order to collect pointer of vectors in your map. For more information see the bellow code:

map<string, vector<char>* > myMap;
string key = "myKey";
vector<char>* myVector = new vector<char>();
myMap[key] = myVector;
myMap[key]->push_back('S');

Upvotes: 0

Michael Chinen
Michael Chinen

Reputation: 18697

To access the mapped value, which in your case is a vector, you just supply the key in square brackets like you did to assign the value. So, to append 'a':

myMap[key].push_back('a');

Upvotes: 1

Related Questions