gpt4 book ai didi

C++ 编译错误(gcc 4.7)

转载 作者:行者123 更新时间:2023-11-28 00:54:58 26 4
gpt4 key购买 nike

我正在尝试在第 5.9 章 Bjarne Stroustrup The C++ Programming Language 的末尾做 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

我做错了什么?

最佳答案

回调函数应该采用 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 << ' ';

关于C++ 编译错误(gcc 4.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com