Crocode
Crocode

Reputation: 3134

How to initialize a string set in C++?

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.

Upvotes: 42

Views: 131944

Answers (6)

Drew Dormann
Drew Dormann

Reputation: 63745

In C++11

Use initializer lists.

std::set<std::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.

std::string init[] = { "John", "Kelly", "Amanda", "Kim" };
std::set<std::string> str(init, init + sizeof(init)/sizeof(init[0]) );

Upvotes: 22

CyberGuy
CyberGuy

Reputation: 2813

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
}

Upvotes: 6

Moshe Gottlieb
Moshe Gottlieb

Reputation: 4003

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));

Upvotes: 2

obataku
obataku

Reputation: 29646

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));

Upvotes: 3

orlp
orlp

Reputation: 117681

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]));

Upvotes: 79

john
john

Reputation: 87959

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

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

Upvotes: 7

Related Questions