How to merge two std::vector in C++? Correct ways to concatenate
Hello everyone! I recently started learning C++ and encountered a task that seems simple, but I can't find an elegant solution. I need to merge two std::vector into one. For example, I have:\n\n```cpp\nstd::vector vec1 = {1, 2, 3, 4, 5};\nstd::vector vec2 = {6, 7, 8, 9, 10};\n```\n\nI want to get a third vector `result` that will contain all elements from `vec1` and then all from `vec2`. That is: `{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`.\n\nThe problem is that I've tried several approaches, but they all seem either incorrect or too cumbersome. For example:\n\n1. I tried using `vec1.insert(vec1.end(), vec2.begin(), vec2.end())`, but this modifies the original vector `vec1`, and I want to keep both original vectors unchanged.\n\n2. I tried writing a loop
No answers yet.
Log in to leave an answer
Blogs