Converting an array to std::vector

suggest change

An array can easily be converted into a std::vector by using std::begin and std::end:

int values[5] = { 1, 2, 3, 4, 5 }; // source array

std::vector<int> v(std::begin(values), std::end(values)); // copy array to new vector

for (auto &x: v) {
    std::cout << x << " ";
}
std::cout << std::endl;
1 2 3 4 5
int main(int argc, char* argv[]) {
    // convert main arguments into a vector of strings.
    std::vector<std::string>  args(argv, argv + argc);
}

A C++11 initializer_list<> can also be used to initialize the vector at once

initializer_list<int> arr = { 1,2,3,4,5 };
vector<int> vec1 {arr};

for (auto & i : vec1) {
    cout << i << endl;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents