2012-08-17 5 views
0

제 5 장. 5.9 Bjarne Stroustrup C++ 프로그래밍 언어 끝 부분에서 11 번 연습을하려고합니다.C++ 컴파일 오류 (gcc 4.7)

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 

내가 뭘 잘못했는지

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 행의 주석을 해제하면?

답변

2

콜백 함수는 이터레이터가 아닌 std::string이어야합니다. for_each은 각 요소 자체를 전달합니다. 고정 예를 들어

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

을 (for_eachstd:: 포함,뿐만 아니라 몇 가지 다른 사소한 차이), this run 참조 : 따라서, 귀하의 기능이 될 것입니다. C++ (11)가 도입 때문에 C에서

는 ++ 11 ( -std=c++0x 또는 -std=c++11를 통해 컴파일러에 대한 접근), 당신도 용기를 통해 약 std::for_each 루프를 걱정할 필요가 없습니다 원거리-에 대한 루프 :

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

+1 범위 기반의 경우 VC2010 (지원하지 않음)으로 대부분의 시간을 소비하지 않았습니다. – hmjd

+0

@hmjd, 그래, C++ 11의 가장 유용한 기능 중 하나인데 거기서 지원되지 않는다고 들었습니다./ – chris

1

이미 chris으로 명시된대로 함수는 const std::string&을 허용해야합니다.

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

추가 컴파일러 플래그 -std=c++0x : 다른 방법으로, 당신은 람다 함수를 사용할 수 있습니다.

+0

C++ 11에 들어갔다면 원거리 - for가 내가 선호하는 선택 일 것이다. 그 옵션을 목록에 추가 할 것입니다. – chris

+0

@chris, g ++ v4.7은 일부 C++ 11 기능을 지원합니다. 왜 그렇게하지 않습니까? – hmjd

+0

좋은 지적. 나는 컴파일러 버전을 알아 차리지 못했다. – chris