C++ maps: Can I increment the value associated with a key?

ZeroBullet

Gawd
Joined
Nov 23, 2001
Messages
530
I am thinking of using maps <string, int> or <string, double> to track values associated with a string key. Is it possible to do a map insert such that the value passed for the int/double portion adds a given number to the existing number in the map?
 
This is what I am getting at:

Code:
for (i=2;i<count;i++)
{
	owerMap.insert(map<string, double>::value_type(tempInput[i], [b]increment here?[/b]));
}
 
Look at T& std::map<K,T>::eek:perator[](K const &), this does precisely what you wish. Otherwise the iterator interface (insert(), find(), et. al.) will let you implement the same thing with different tradeoffs (more verbosity but more information).

The STL is very useful for solving this type of problem, there are many ways to implement it, each with different tradeoffs.
 
ZeroBullet said:
This is what I am getting at:

Code:
for (i=2;i<count;i++)
{
	owerMap.insert(map<string, double>::value_type(tempInput[ i ], [b]increment here?[/b]));
}

Out of curiosity - and possibly because your question confuses me a lot - what's stopping you from just putting varName++ or varName + x wherever you use the double or integer variable?
 
Here's a small example of what I think you want.

Code:
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
    map<string, double> keyword;
    keyword["entry1"] = 1.4;
    [color=yellow]keyword["entry1"] += 2.6;[/color]
    cout << endl << keyword["entry1"] << endl;
}
 
UMCPWintermute said:
Out of curiosity - and possibly because your question confuses me a lot - what's stopping you from just putting varName++ or varName + x wherever you use the double or integer variable?

I'm not sure I understand your question either heh. But I need to increment and store multiple values associated with multiple names.
 
Shadow2531 said:
Here's a small example of what I think you want.

Code:
    map<string, double> keyword;
    keyword["entry1"] = 1.4;
    [color=yellow]keyword["entry1"] += 2.6;[/color]
    cout << endl << keyword["entry1"] << endl;
}

So if I had
mymap["Bob"] = 100;
mymap["Bob"] +=250;

Then the value associated with Bob should be 350?
If the answer is this simple then I'm a n00b heh :eek:
 
Back
Top