I'm currently studying the book Accelerated C++ (Koening/Moo) and I'm having trouble with one of the exercises. The task is to write a program which takes as an input some sequence of words which it then stores in a map<string, int>
. The strings are the words entered and the associated int
is the number of times each word occurs. You then have to sort the words by the number of times they occur; that is, by the value and not the key. You can't sort a map by the value, so I tried to copy the elements to a vector instead, which I intended to sort using a predicate. Unfortunately, all I get is a screen full of errors from g++. They seem to stem from the same place - putting the elements of my map into my vector, which I try to do like this:
int main()
{
map<string, int> counters;
cout << "Enter some words followed by end-of-file (ctrl-d): ";
string word;
while (cin >> word)
++counters[word];
// Maps cannot be sorted by values, so pass the elements of counters to a vector.
vector<map<string, int> > vec_counters;
map<string, int>::const_iterator it = counters.begin();
while (it != counters.end()) {
vec_counters.push_back(*it);
++it;
}
}
This is obviously just the first part, but I can't get even this to compile. I get the following error:
32:31: error: no matching function for call to std::vector, int> >::push_back(const std::pair, int>&)’ /usr/include/c++/4.5/bits/stl_vector.h:741:7: note: candidate is: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::map, int>, _Alloc = std::allocator, int> >, value_type = std::map, int>]
What am I doing wrong?
I'm pretty sure you aren't looking for a vector of maps:
#include <map>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<string, int> counters;
cout << "Enter some words followed by end-of-file (ctrl-d): ";
string word;
while (cin >> word)
++counters[word];
vector<std::pair<string, int> > vec(counters.begin(), counters.end());
}