-1

The accepted answers in

  1. Convert char** (c) to vector<string> (c++)
  2. copying c array of strings into vector of std::string
  3. converting an array of null terminated const char* strings to a std::vector< std::string >

populate the vector at the same time as declaring it:

vector<string> vec(cArray, cArray + cArrayLength)

But what if I need to do it separately because I need to expand the scope of the vector, e.g. in

vector<string> vec;
if (some_condition)
    // copy a char** to vec
else
    // copy another char** to vec
do_something(vec);

How do I copy the arrays then?

Community
  • 1
  • 1
Gnubie
  • 2,587
  • 4
  • 25
  • 38

3 Answers3

2

std::vector provides an assignment operator:

std::vector<std::string> vec;
if (some_condition)
    // copy a char** to vec
    vec = std::vector<std::string> vec(cArray, cArray + cArrayLength);
else
    // copy another char** to vec
    vec = std::vector<std::string> vec(cArray, anotherCArray + anotherCArrayLength )
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
1

You can always use the copy constructor as

if(cond)
{
    vec = std::vector<std::string>(std::begin(arr1), std::end(arr1));
}
else
{
    vec = std::vector<std::string>(std::begin(arr2), std::end(arr2));
}
Harish krupo
  • 23
  • 1
  • 7
1

A couple of answers have already pointed to creating a temporary object, then assigning the result to your destination. As long as you're using C++11 (or later) where this will be done as a move assignment, that's generally quite acceptable.

Another possibility that will work well with older compilers (and new ones) would be something like:

char **src;
size_t len;

if (cond) { 
    src = cArray;
    len = cArrayLen;
}
else {
    src = CAnotherArray;
    len = CAnotherArrayLen;
}

vector<string> vec(src, src+len);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111