Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a string set in C++?

Tags:

c++

string

set

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.

like image 946
Crocode Avatar asked Sep 08 '12 19:09

Crocode


People also ask

Can we initialize string in C?

'C' also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way, char first_name[ ] = "NATHAN"; The name of Strings in C acts as a pointer because it is basically an array.

How do you initialize a string?

Initialize a string by passing a literal, quoted character array as an argument to the constructor. Initialize a string using the equal sign (=). Use one string to initialize another. These are the simplest forms of string initialization, but variations offer more flexibility and control.

How do you declare a string variable in C?

Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.


2 Answers

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])); 
like image 199
orlp Avatar answered Sep 20 '22 06:09

orlp


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]) ); 
like image 27
Drew Dormann Avatar answered Sep 20 '22 06:09

Drew Dormann