Rock
Rock

Reputation: 197

How to initialize an unorderd_set using C++ (g++ compiler)?

I observe the following error while trying to compile a sample code with g++

#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

Solved by using compiler option "-std=c++11".

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

Upvotes: 0

Views: 6054

Answers (2)

Rock
Rock

Reputation: 197

Solved by using compiler option "-std=c++11".

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

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

Works for me.

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

You could try one of the following alternative forms, all of which work with clang 6.0:

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

Upvotes: 1

Related Questions