2014-09-28 71 views
0

我觀察下面的錯誤,而試圖編譯一個示例代碼使用g ++如何使用C++(g ++編譯器)初始化unorderd_set?

#include <iostream> 
#include <unordered_set> 

int main() { 
    std::unordered_set<std::string> second ({"red","green","blue"}); // init list 
    std::unordered_set<std::string> second1 {"red", "green", "blue"}; // Marcelo Cantos 
    std::unordered_set<std::string> second2{{"red", "green", "blue"}}; // Marcelo Cantos 
    std::unordered_set<std::string> second3 = {"red", "green", "blue"};// Marcelo Cantos 
    return 0; 

} 

$ gcc -o wp -Wall -Wextra test_set.cpp 
test_set.cpp:5:45: error: expected expression 
    std::unordered_set<std::string> second ({"red","green","blue"})... 
             ^
test_set.cpp:6:43: error: expected ';' at end of declaration 
    std::unordered_set<std::string> second1 {"red", "green", "blue"}; 
             ^
              ; 
test_set.cpp:7:43: error: expected ';' at end of declaration 
    std::unordered_set<std::string> second2{{"red", "green", "blue"}}; 
             ^
              ; 
test_set.cpp:8:36: error: non-aggregate type 'std::unordered_set<std::string>' cannot be initialized with an initializer list 
    std::unordered_set<std::string> second3 = {"red", "green", "blue"}; 
           ^  ~~~~~~~~~~~~~~~~~~~~~~~~ 
4 errors generated. 


$ g++ --version 
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) 
Target: x86_64-apple-darwin13.3.0 
Thread model: posix 

通過使用編譯器選項「-std = C++ 11」解決。

$克++ -o TEST_SET -Wall -Wextra -std = C++ 11 test_set.cpp

+2

您應該編譯爲[C++ 11](http://en.wikipedia.org/wiki/C++11)即使用'g ++ -Wall -Wextra -std = C++ 11 test_set.cpp -o wp' – 2014-09-28 09:11:54

+1

'#include '。 – juanchopanza 2014-09-28 09:12:18

+0

-std = C++ 11工作!謝謝,巴西爾。那很快! – Rock 2014-09-28 11:17:25

回答

2

通過使用編譯器選項 「-std = C++ 11」 解決。

$ g++ -o test_set -Wall -Wextra -std=c++11 test_set.cpp 
1

我的作品。

Apple LLVM version 6.0 (clang-600.0.51) (based on LLVM 3.5svn) 
Target: x86_64-apple-darwin13.4.0 
Thread model: posix 

你可以嘗試以下的替代形式之一,所有這些鏗鏘6.0工作:

…second{"red", "green", "blue"}; 
…second{{"red", "green", "blue"}}; 
…second = {"red", "green", "blue"}; 
+0

以上所有僅在編譯時使用-std = C++ 11時纔有效。 編輯與每個案件的錯誤消息。 – Rock 2014-09-28 11:18:38

+0

@搖滾:是的。我很習慣現在用C++ 11工作,我沒有想到要問。 – 2014-09-29 12:44:04