2

In my project I want to insert keys to a map. All new keys should get the value 1.0, but existing keys should be incremented by 1.

Here's the code

vector <string> pairs; map<string, float> two; map <string, float>::iterator it; string a = "a"; string b = "b"; string c = "a"; pairs.push_back(a); pairs.push_back(b); pairs.push_back(c); for(int i=0; i<pairs.size(); i++) { it = two.find(string(pairs[i]) ); if(i==0) { two[string(pairs[i])]=1.0; } else if ( it == two.end() ) { it->second = it->second + 1.0; //after this line ^,my compiler stop working } else { two[string(pairs[i])]=1.0; } } 

After this, the object should be

a 2 b 1 

How can I do so.

4 Answers 4

2

The easiest and most efficient solution is:

for (auto const& s : pairs) two[s] += 1.0; 

This works because the [] operator on maps automatically creates an entry if the key isn't present, using the default value constructor. For floats, the default constructor produces a 0.0.

Since [] returns a reference, no additional lookup will be done in order to increment the value.

Sign up to request clarification or add additional context in comments.

Comments

1
else if ( it == two.end() ) { it->second = it->second + 1.0; 

Above line of code need to correct as follows

else if ( it != two.end() ) ^^^ { it->second = it->second + 1.0; 

More than that:

it = two.find(string(pairs[i]) ); 

Above line can rewrite as follows

it = two.find(pairs[i] ); 

1 Comment

thanks alot, now it works like it should worked :) !
1

The STL was designed to do this efficiently, and it pays to see how.

But first, note that in your code, the lines

two.find(string(pairs[i]) ); two[string(pairs[i])]=1.0; 

perform two lookups, which is a bit of a waste.

If you look at the signature for map::insert, you can see that the return value is std::pair<iterator, bool>. The second is a boolean indicating whether the element was actually inserted. The first is an iterator to either the previous element (if it existed, in which case it was not overwritten), or to the new element.

So, the way to do it efficiently is to write

auto ins = two.insert(make_pair(pairs[i], 0)); ins.first->second += 1; 

Comments

0

There should be it != two.end() instead of it == two.end()

I think also the 1st condition (i==0) checking can be skipped

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.