Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly initialize vector<char *> with string literal?

The problem comes from an exercise on C++ Primer 5th Edition:

Write a program to assign the elements from a list of char* pointers to C-style character strings to a vector of strings.

----------------Oringinal Question------------

First I try the following somewhat direct way:

vector<char *> vec = {"Hello", "World"};
vec[0][0] = 'h';

But compiling the code I get a warning:

temp.cpp:11:43: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     vector<char *> vec = {"Hello", "World"};
                                           ^ 

And running the ./a.out I get a

Segmentation fault (core dumped)

I think it is because I try to write to a const char. So I try another way:

char s1[] = "Hello", s2[] = "World";
vector<char *> vec = {s1, s2};
vec[0][0] = 'h';

It is OK this time. But it seems a little tedious. Is there any other elegant way to initialize a vector with string literal?

like image 905
Warbean Avatar asked Jan 23 '15 12:01

Warbean


People also ask

What is the correct way to initialize vector in C++?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.


1 Answers

I think the char vs const char difference doesn matter much in this task.

For the actual copy, use a fill constructor with iterator arguments:

vector<const char*> vc = {"hello","world"};
vector<string> vs(vc.begin(), vc.end());

See a working example.

If there's a need for editable chars in the source, just use the second version you posted:

char s1[] = "Hello", s2[] = "World";
vector<char *> vec = {s1, s2};

Supplement: The arguments of main, argc and argv, are a great example of

a list of char* pointers to C-style character strings

See how argc and argv get translated into a vector of string.

like image 155
Wolf Avatar answered Oct 26 '22 09:10

Wolf