count() in map

closed account (1vf9z8AR)
I am new to maps in c++. Can you tell me what is wrong with my code?

I want the number of occurrences of the second string

Issue-
currentcnt is always 0. I did correct insertion to the map.

1
2
3
4
5
     map<string,string>mp;
     // body of code
     map<string,string>::iterator it;
    for(it=mp.begin();it!=mp.end();it++)
        int currentcnt=mp.count(it->second);


Last edited on
By the way can you use sort from <algorithm> on map?
> I want the number of occurrences of the second string

std::map::count() gives the count of a key (the first string).
This yields either zero (key is not present) or one since the map does not allow duplicate keys.

To count the number of occurrences of the values (the second string), iterate through the map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <map>
#include <iomanip>

template < typename KEY_TYPE, typename MAPPED_TYPE, typename KEYCMP, typename ALLOCATOR >
std::size_t count_mapped_values( const std::map<KEY_TYPE,MAPPED_TYPE,KEYCMP,ALLOCATOR>& map, const MAPPED_TYPE& value )
{
    std::size_t cnt = 0 ;
    for( const auto& pair : map ) if( value == pair.second ) ++cnt ;
    return cnt ;
}

int main()
{
    std::map< std::string, std::string > map { { "one", "1" }, { "two", "2" }, { "three", "3" },
                                               { "un", "1" }, { "seux", "2" },
                                               { "eins", "1" }, { "zwei", "2" },
                                               { "dos", "2" } } ;

    for( int i = 1 ; i < 5 ; ++i )
    {
        std::cout << "count of value " << std::quoted( std::to_string(i) ) << " : "
                  << count_mapped_values( map, std::to_string(i) ) << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/9d4707e34c06fa70



> By the way can you use sort from <algorithm> on map?

No, for two reasons: the keys in a map are immutable, and its iterator is not a random access iterator.

Note that the elements in a std::map are already ordered (sorted) on keys.

Last edited on
Topic archived. No new replies allowed.