C++ nested for loop in the <map>

How to write the nested for loop to find the repeated value (Duplicate value) in the <map>?

In here:
map < string, int > myMap;
String is word
int is # of frequency

How can i use the nested For loop to find the repeated # of frequency inside my map? and if its same then cout the repeated one...

....

1
2
3
4
5
6
7
8
9
10
11
 map < string, int > myMap;
  while (myfile >> words)
    {
     // Inc the count
      myfile[words]++;
}

// nested loop
// compare if there is repeated # of frequency 
// cout the repeated value
Last edited on
1
2
3
4
5
6
7
8
9
10
set<int> alreadySeen;

for (auto& value : myMap)
{
  if (alreadySeen.find(value.second) != alreadySeen.end())
  {
     cout << value.second;
  }
  alreadySeen.insert(value.second);
}
I'm not sure, but I think you can also test directly on the attempt to insert, so killing two birds with one stone.
1
2
3
4
5
set<int> alreadySeen;
for (auto& value : myMap)
{
  if (!alreadySeen.insert(value.second).second)  cout << value.second << " is a repeat\n";
}
This seems like continuation of http://www.cplusplus.com/forum/beginner/243544/
where there essentially is a solution already. (If it is, then this thread is almost a double-post.)

Why do you want to use "nested loop"?
to find out if i have a repeated #frequency as value in my map...
If a nested loop must be used:

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
for( const auto& pair : myMap ) // outer loop
{
    std::cout << pair.first << ' ' << pair.second ;

    int dup_count = 0 ;
    for( const auto& another_pair : myMap ) // inner loop
    {
        if( another_pair.second == pair.second ) ++dup_count ;
    }
    if( dup_count > 1 ) std::cout << "  duplicated " << dup_count << " times." ;

    std::cout << '\n' ;
}

// or, C++98

typedef std::map< std::string, int >::const_iterator iterator ;

for( iterator iter = myMap.begin() ; iter != myMap.end() ; ++iter ) // outer loop
{
    std::cout << iter->first << ' ' << iter->second ;

    int dup_count = 0 ;
    for( iterator another_iter = myMap.begin() ; another_iter != myMap.end() ; ++another_iter ) // inner loop
    {
        if( another_iter->second == iter->second ) ++dup_count ;
    }
    if( dup_count > 1 ) std::cout << "  duplicated " << dup_count << " times." ;

    std::cout << '\n' ;
}
to find out if i have a repeated #frequency as value in my map...

If the question is "How to find repeated values?", then why do you ask: "How to write a loop?"

Is the real question one of those, or is it: "How to use std::map?"


The "How to find repeated values?" is about algorithm. Logic.
It does not really care about the choice of container.

The "How to use std::map?" is about syntax of specific container.
Topic archived. No new replies allowed.