41

I have a few words to be initialized while declaring a string set.

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

/*str has to contain some names like "John", "Kelly", "Amanda", "Kim".*/

I don't want to use str.insert("Name"); each time.

Any help would be appreciated.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Crocode
  • 3,056
  • 6
  • 26
  • 31
  • 2
    You can take advantage of initializer lists if you're using C++11. See #5 in this [constructor list](http://en.cppreference.com/w/cpp/container/set/set) and the relevant part of Stroustrup's [C++11 FAQ](http://stroustrup.com/C++11FAQ.html#init-list). – chris Sep 08 '12 at 19:28

6 Answers6

78

Using C++11:

std::set<std::string> str = {"John", "Kelly", "Amanda", "Kim"};

Otherwise:

std::string tmp[] = {"John", "Kelly", "Amanda", "Kim"};
std::set<std::string> str(tmp, tmp + sizeof(tmp) / sizeof(tmp[0]));
orlp
  • 112,504
  • 36
  • 218
  • 315
21

In C++11

Use initializer lists.

set<string> str { "John", "Kelly", "Amanda", "Kim" };

In C++03 (I'm voting up @john's answer. It's very close what I would have given.)

Use the std::set( InputIterator first, InputIterator last, ...) constructor.

string init[] = { "John", "Kelly", "Amanda", "Kim" };
set<string> str(init, init + sizeof(init)/sizeof(init[0]) );
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
8

There's lots of ways you can do this, here's one

string init[] = { "John", "Kelly", "Amanda", "Kim" };
set<string> str(init, init + 4);
john
  • 85,011
  • 4
  • 57
  • 81
6

if you are not c++0x:

You should look at boost::assign

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

Also take a look at:

Using STL/Boost to initialize a hard-coded set<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
}
Community
  • 1
  • 1
CyberGuy
  • 2,783
  • 1
  • 21
  • 31
4

There's multiple ways to do this. Using C++11, you can try either...

std::set<std::string> set {
  "John", "Kelly", "Amanda", "Kim"
};

... which uses an initializer list, or std::begin and std::end...

std::string vals[] = { "John", "Kelly", "Amanda", "Kim" };
std::set<std::string> set(std::begin(vals), std::end(vals));
obataku
  • 29,212
  • 3
  • 44
  • 57
2

Create an array of strings(C array) and initialize the set with it's values (array pointers as iterators):
std::string values[] = { "John", "Kelly", "Amanda", "Kim" };
std::set s(values,values + sizeof(values)/sizeof(std::string));

Moshe Gottlieb
  • 3,963
  • 25
  • 41