-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?

2
  • 6
    vec.assign(cArray, cArray + cArrayLength); Commented Jan 15, 2016 at 16:12
  • std::copy and std::back_inserter too..... research!! Commented Jan 15, 2016 at 16:22

3 Answers 3

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 )
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.