gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
c++ combine vector
- User
c++ combine vector
- Assistant
To combine two vectors in C++, you can use the
std::vector::insert()function or thestd::vector::reserve()function.Using
std::vector::insert():c++#include <iostream> #include <vector> int main() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {4, 5}; v1.insert(v1.end(), v2.begin(), v2.end()); for (int i : v1) { std::cout << i << " "; } std::cout << std::endl; return 0; }Output:
1 2 3 4 5Using
std::vector::reserve()andstd::vector::push_back():c++#include <iostream> #include <vector> int main() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {4, 5}; v1.reserve(v1.size() + v2.size()); for (int i : v2) { v1.push_back(i); } for (int i : v1) { std::cout << i << " "; } std::cout << std::endl; return 0; } - User
c++ copy vector to replace another vector
- Assistant
To copy the contents of one vector to another vector in C++, you can use the
std::vector::operator=or thestd::vector::assign()function.Using
std::vector::operator=:c++#include <iostream> #include <vector> int main() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2; v2 = v1; for (int i : v2) { std::cout << i << " "; } std::cout << std::endl; return 0; }Output:
1 2 3Using
std::vector::assign():c++#include <iostream> #include <vector> int main() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2; v2.assign(v1.begin(), v1.end()); for (int i : v2) { std::cout << i << " "; } std::cout << std::endl; return 0; }