3

my question is that I have made multimap.Here is the partial code.

        if(binary_search(final.begin() , final.end() , answer ) )
            {

            final[answer] =    

            }
            else
            {
                final.insert(pair<string,int>(answer , 1 ) );
            }

Here answer is a string and final is a multimap of <string,int>. Now what I want is that if the string answer is present then increment(modify) the value of int. How can I do this? I want to increment the value of int by one if the string element is already present?

Regards.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
InspiredCoder
  • 394
  • 6
  • 22

2 Answers2

4

If you want keys to be unique then use map. Then you can simply do final[answer]++. Note that map::operator[] will insert the key into the map if it doesn't exists already. The value will be default constructed during this insertion and the reference to this default constructed value is returned. If the key exists already then it returns the reference to the value element.

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • oh yeah :) now how would I search in a map then? – InspiredCoder Apr 02 '12 at 18:06
  • `++final[answer]` is the preferred method of incrementing, unless you specifically need the pre-incremented value. – Chris Apr 02 '12 at 18:07
  • @InspiredCoder: use `map::find`. – Naveen Apr 02 '12 at 18:07
  • 1
    @InspiredCoder - if the only search you do is the one in your question, then you don't need to search at all. You may replace the all of the code in the question with a simple `++final[answer]`. If the entry already exists, it will be incremented. If the entry doesn't exist, it will be created (with a value of `0`), and incremented. No explicit search required. – Robᵩ Apr 02 '12 at 18:11
1

use a std::map if the key is unique.

If you need a multimap (i.e. you need multiple entries with the same key), use ?std::lower_bound:

multimap::iterator it = mmap.lower_bound(key);
while (it != mmap.end() && it->first == key)
{
   // *it is a key-value pair, where you can modify the value
   it->second.Modify();
   ++it;
}

 
peterchen
  • 40,917
  • 20
  • 104
  • 186