如何在C++中初始化字符串集?

Cro*_*ode 34 c++ string set

在声明字符串集时,我有几个要初始化的单词.

...
using namespace std;
set<string> str;

/*str has to contain some names like "John", "Kelly", "Amanda", "Kim".*/
Run Code Online (Sandbox Code Playgroud)

我不想str.insert("Name");每次都使用.

任何帮助,将不胜感激.

orl*_*rlp 70

使用C++ 11:

std::set<std::string> str = {"John", "Kelly", "Amanda", "Kim"};
Run Code Online (Sandbox Code Playgroud)

除此以外:

std::string tmp[] = {"John", "Kelly", "Amanda", "Kim"};
std::set<std::string> str(tmp, tmp + sizeof(tmp) / sizeof(tmp[0]));
Run Code Online (Sandbox Code Playgroud)


Dre*_*ann 15

在C++ 11中

使用初始化列表.

set<string> str { "John", "Kelly", "Amanda", "Kim" };
Run Code Online (Sandbox Code Playgroud)

在C++ 03中 (我正在投票@约翰的回答.它与我给出的非常接近.)

使用std::set( InputIterator first, InputIterator last, ...)构造函数.

string init[] = { "John", "Kelly", "Amanda", "Kim" };
set<string> str(init, init + sizeof(init)/sizeof(init[0]) );
Run Code Online (Sandbox Code Playgroud)


joh*_*ohn 8

有很多方法可以做到这一点,这是一个

string init[] = { "John", "Kelly", "Amanda", "Kim" };
set<string> str(init, init + 4);
Run Code Online (Sandbox Code Playgroud)


Cyb*_*Guy 6

如果你不是c ++ 0x:

你应该看一下boost :: assign

http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/index.html#list_of

另外看看:

使用STL/Boost初始化硬编码集<vector <int >>

#include <boost/assign/list_of.hpp> 
#include <vector>
#include <set>

using namespace std;
using namespace boost::assign;

int main()
{
    set<int>  A = list_of(1)(2)(3)(4);

    return 0; // not checked if compile
}
Run Code Online (Sandbox Code Playgroud)