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.
'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.
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.
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.
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]));
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]) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With