Search code examples
c++gcccompilationg++gcc4.7

C++ Compilation error(gcc 4.7)


I'm trying to do 11 exercise at the end of Chapter 5.9 Bjarne Stroustrup The C++ Programming Language.

  1 #include <iostream>
  2 #include <string>
  3 #include <vector>
  4 #include <algorithm>
  5 
  6 void print(std::vector<std::string>::const_iterator str) {
  7    std::cout << *str;
  8 }
  9 
 10 int main(void) {
 11    std::vector<std::string> words;
 12    std::string tmp;
 13 
 14    std::cin >> tmp;
 15    while (tmp != "Quit") {
 16       words.push_back(tmp);
 17       std::cin >> tmp;
 18    }
 19 
 20    for_each(words.begin(), words.end(), print);
 21 
 22    return 0;
 23 }

When I uncomment 20 line I get this error:

In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from 5.9.11.cpp:4:
/usr/include/c++/4.7/bits/stl_algo.h: In instantiation of ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >; _Funct = void (*)(__gnu_cxx::__normal_iterator<const std::basic_string<char>*, std::vector<std::basic_string<char> > >)]’:
5.9.11.cpp:20:44:   required from here
/usr/include/c++/4.7/bits/stl_algo.h:4442:2: error: could not convert ‘__first.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<std::basic_string<char>*, std::vector<std::basic_string<char> > >()’ from ‘std::basic_string<char>’ to ‘__gnu_cxx::__normal_iterator<const std::basic_string<char>*, std::vector<std::basic_string<char> > >’

Compile command :

g++ prog.cpp -o prog -Wall

What i did wrong?


Solution

  • The callback function should take an std::string, not an iterator. for_each passes each element itself. Thus, your function would become:

    void print(const std::sting &str) {
        std::cout << str << ' '; //note I separated the words
    }
    

    For a fixed example (including the std:: on for_each, as well as a couple other minor differences), see this run.

    In C++11 (accessible to your compiler through -std=c++0x or -std=c++11), you need not even worry about std::for_each to loop through the container because C++11 introduced the ranged-for loop:

    for (const std::string &str : words)
        std::cout << str << ' ';