1

What is the correct way to build an std::vector<std::string> from an std::initializer_list<char const*>? I can iterate through the initializer list and manually build up the vector as such:

std::initializer_list<char const*> values;
std::vector<std::string> vec;
for(auto v : values) {
    vec.push_back(v);
}

Seems quite verbose. Suggestions?

0

1 Answer 1

1

std::vector has a constructor that accepts an iterator range as input, as long as the dereferenced values are convertible to the vector's value_type:

std::vector<std::string> vec(values.begin(), values.end());
Sign up to request clarification or add additional context in comments.

1 Comment

@MooingDuck I edited your proof to put a delimiter between the vector elements to make it clearer that the constructor did actually work correctly: coliru.stacked-crooked.com/a/914f0fa0c4f56ea4

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.