How to append one vector to the end of another in C++ (append vector to vector)
Hello! I just started learning C++ and STL. I have two vectors, and I want to append all elements of the second vector to the end of the first one. I tried several ways, but none work as I expected.
Here is my code:
```cpp
#include
#include
int main() {
std::vector vec1 = {1, 2, 3};
std::vector vec2 = {4, 5, 6};
// Trying to append vec2 to vec1
vec1.append(vec2); // Error: no method append
// Trying via insert
vec1.insert(vec2.begin(), vec2.end()); // Compilation error
// Trying via push_back in a loop
for (int i = 0; i < vec2.size(); i++) {
vec1.push_back(vec2[i]); // Works, but looks terrible
}
return 0;
}
```
The first option doesn't compile at all because std
No answers yet.
Log in to leave an answer
Blogs