0

I have a vector of type string which contains the following:

tpNums contains:        2   15   38   43   50           5   14   16   29   53

I am attempting to take the contents of the vector and count the number of times each number in the vector appears in this case they all only appear once; following code:

std::map<std::string, std::size_t> results;
    std::for_each(begin(tpNums), end(tpNums), [&](std::string const& s)
    {
        ++results[s];

    });

My question is, how do I output the contents of the resultant map?

Is there an easier to solve my problem or is this the only way?

EDIT:

I have tried this:

std::map<std::string, std::size_t> results;
    std::for_each(begin(tpNums), end(tpNums), [&](std::string const& s)
    {
        ++results[s];
        cout << results[s];

    });

OUTPUT:1112

I don't think I am outputting the correct thing, I have tried different ways but they either show an error or output the wrong thing

Dave Cribbs
  • 809
  • 1
  • 6
  • 16

1 Answers1

2

To dump the content of the map, you could use usual map::cbegin/map::cend loop:

for (auto it = results.cbegin(); it != results.cend(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

or, as @leemes mentioned, just

for (auto& pair : results)
    std::cout << pair.first << " => " << pair.second << '\n';

And if you have pre-C++11 compiler, then map::begin/map::end:

for (std::map<string, size_t>::iterator it = result.begin(); it != result.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';
AlexD
  • 32,156
  • 3
  • 71
  • 65
  • oh ok this worked but I dont think my map is counting the correct things, it shows this `=> 2` `2 15 38 43 50 => 1` `5 14 16 29 53 => 1` I want it to count each individual number but it is counting the series of numbers, is it because of the extra spaces that i have in the vector? – Dave Cribbs Oct 17 '14 at 23:28
  • "5 14 16 29 " is a string. No matter how many spaces there, it is just *one* long string. If you want to do something with the single "sequences of digits", you first have to break down the string into the chunks that you consider one entity (or possibly even convert them to numbers). – Oguk Oct 17 '14 at 23:33
  • It seems that tpNums contains 4 strings: `"", "2 15 38 43 50", "", "1 5 14 16 29 53"`. You need to split them into individual numbers first. See http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c. (For simplicity you could first concatenate all strings in `tpNum` in one long string using `" "` as a delimiter, then split the resulting string into a vector, and then do your counting loop.) – AlexD Oct 17 '14 at 23:33
  • If you had C++11, you wouldn't write hand-crafted iterator for loops. You'd use range-based for loops :) – leemes Oct 17 '14 at 23:41