2016-05-12 3 views
1

マップをC++で連想コンテナとして使用しようとしています。私は直接C++ Primerのうち、この例をコピー:C++ - map-error: 'class int'以外の 'w'のメンバ 'first'へのリクエスト

#include <stdio.h> 
#include <iostream> 
#include <string> 
#include <map> 

using namespace std; 

int main() 
{ 
    map<string, size_t> word_count; 
    string word; 

    while (cin >> word) 
     ++word_count[word]; 
    for (const auto &w : word_count) 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 

    return 0; 
} 

私は試してみて、それを実行すると、私は「エラーを取得:非クラス型である 『最初の』 『W』のメンバーの要求、 "のconst int型" C++ Primerの著者は、GNU 4.7.0を使用していると述べています。私はminGW(TDM-GCC-32)とVisual C++ 14を使ってみました。なぜこのエラーが出ますか?

+2

は再現することはできません。実際のコードを入力してください。 – SergeyA

+2

これはGCCとClangの両方で[Coliru](http://coliru.stacked-crooked.com/)でコンパイルされます。 – chris

+3

コンパイラがC++ 11モードに設定されていることを確認してください。 –

答えて

3

言語標準のバージョンが十分に新しくコンパイルされていません。

あなたが言う、C++ 98でコンパイルした場合は、以下を参照してくださいになります。

g++ -std=c++98 -o main a.cpp                              1 
a.cpp: In function ‘int main()’: 
a.cpp:15:22: error: ISO C++ forbids declaration of ‘w’ with no type [-fpermissive] 
    for (const auto &w : word_count) 
        ^
a.cpp:15:26: warning: range-based ‘for’ loops only available with -std=c++11 or -std=gnu++11 
    for (const auto &w : word_count) 
         ^
a.cpp:16:19: error: request for member ‘first’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 
       ^
a.cpp:16:44: error: request for member ‘second’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 
              ^
a.cpp:16:58: error: request for member ‘second’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 

これはC++ 11で導入range-based for loopによるものです。
はしてコンパイルしてみます。

g++ -std=c++11 -o main a.cpp 

(もちろん、それはあなたが使用しているコンパイラによって異なります)

関連する問題