Converting an array to std::vector
suggest changeAn array can easily be converted into a std::vector by using std::begin and std::end:
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int values[]{1, 2, 3, 4, 5};
std::vector<int> numbers(std::begin(values), std::end(values));
for (int number : numbers) {
std::cout << number << ' ';
}
std::cout << '\n';
}
1 2 3 4 5
#include <string>
#include <vector>
int main(int argc, char* argv[]) {
// Convert the program arguments into a vector of strings.
std::vector<std::string> args(argv, argv + argc);
}
Since C++17, class template argument deduction also lets a vector be initialized directly from a braced list:
#include <iostream>
#include <vector>
int main() {
std::vector numbers{1, 2, 3, 4, 5};
for (int number : numbers) {
std::cout << number << '\n';
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents