Repetitive values in map(values)

Hello everyone,

I am using std::map<int,string> abc

i am struggling to find repetitive values in map
abc[1]="i am ok"
abc[2]="i am not ok"
abc[3]="i am dash dash"
abc[4]="i am ok" // error
abc[5]="test"

abc[4]is error
Thanks
In this situation a std::map is not going to give you any advantage over a std::vector.
In either case, you need to iterate over the entire container to find duplicates.

What error ? What compiler ?

No error with VS 2015
i am using vs 2012
i have to flag both abc[1]& abc[4] (since duplicate values exist) or store in some other vector
An error shouldn't occur.


i am struggling to find repetitive values in map


If your objective is to find repeating values, a multimap (rather than a map) will help. Entries with multiple index values imply repeating values.

Checking to see if an entry already exists.
1
2
3
4
if (abc.find(4) != abc.end())
{
    cout << "map already contains key 4";
}
Last edited on
Here's code to count and report how many times a string occurs:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <map>
#include <iostream>
#include <string>
using namespace std;

//  Insert with duplicate counting
void do_insert (map<string,int> & abc, const string & str)
{   map<string,int>::iterator    iter;
    pair<string,int>    pr (str,1);
    
    iter = abc.find (str);
    if (iter != abc.end())
    {   //  str already in map
        iter->second++;     //  Increment duplicate count
        return;
    }
    //  str not found
    abc.insert (pr);   
}            

void report_duplicates (const map<string,int> & abc)
{   map<string,int>::const_iterator    citer; 

    for (citer= abc.begin(); citer!=abc.end(); citer++)
    {   if (citer->second > 1)
            cout << citer->first << " occurred " << citer->second << " times." << endl;
    }
}
            
int main ()
{   map<string,int>    abc;   //  note types reversed
    
    do_insert (abc, "i am ok");
    do_insert (abc, "i am not ok");
    do_insert (abc, "i am dash dash");
    do_insert (abc, "i am ok");  // Duplicate 
    do_insert (abc, "test");
    report_duplicates (abc);
    system ("pause");
    return 0;
}    
i am ok occurred 2 times.
Press any key to continue . . .

Topic archived. No new replies allowed.