【问题标题】:C++ Compilation error(gcc 4.7)C++ 编译错误(gcc 4.7)
【发布时间】:2012-08-17 16:07:36
【问题描述】:

我正在尝试在第 5.9 章 Bjarne Stroustrup C++ 编程语言的末尾做 11 个练习。

  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 }

当我取消注释 20 行时,我收到此错误:

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> > >’

编译命令:

g++ prog.cpp -o prog -Wall

我做错了什么?

【问题讨论】:

    标签: c++ gcc compilation g++ gcc4.7


    【解决方案1】:

    回调函数应该采用std::string,而不是迭代器。 for_each 传递每个元素本身。因此,您的函数将变为:

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

    有关固定示例(包括for_each 上的std::,以及其他一些细微差别),请参阅this run

    在 C++11 中(您的编译器可通过 -std=c++0x-std=c++11 访问),您甚至不必担心 std::for_each 循环容器,因为 C++11 引入了 ranged-for 循环:

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

    【讨论】:

    • +1 对于基于范围,我大部分时间都没有使用它,因为我大部分时间都在使用 VC2010(它不支持它)。
    • @hmjd,是的,我发现这是 C++11 最有用的特性之一,并且听说那里不支持它:/
    【解决方案2】:

    正如chris 所述,print() 函数应该接受const std::string&amp;。作为替代方案,您可以使用 lambda 函数:

    std::for_each(words.begin(),
                  words.end(),
                  [](const std::string& a_s)
                  {
                      std::cout << a_s << "\n";
                  });
    

    添加编译器标志-std=c++0x

    【讨论】:

    • 好建议,但如果我们要进入 C++11,ranged-for 将是我的首选。我想我会将该选项添加到列表中。
    • @chris,g++ v4.7 支持一些 C++11 特性,为什么不呢?
    猜你喜欢
    • 2013-09-01
    • 2013-03-19
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多