How do I concatenate two std::vector
s?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
To be honest, you could fast concatenate two vectors by copy elements from two vectors into the other one or just only append one of two vectors!. It depends on your aim.
Method 1: Assign new vector with its size is the sum of two original vectors' size.
Method 2: Append vector A by adding/inserting elements of vector B.
This solution might be a bit complicated, but
boost-range
has also some other nice things to offer.Often ones intention is to combine vector
a
andb
just iterate over it doing some operation. In this case, there is the ridiculous simplejoin
function.For large vectors this might be an advantage, as there is no copying. It can be also used for copying an generalizes easily to more than one container.
For some reason there is nothing like
boost::join(a,b,c)
, which could be reasonable.If what you're looking for is a way to append a vector to another after creation,
vector::insert
is your best bet, as has been answered several times, for example:Sadly there's no way to construct a
const vector<int>
, as above you must construct and theninsert
.If what you're actually looking for is a container to hold the concatenation of these two
vector<int>
s, there may be something better available to you, if:vector
contains primitivesconst
containerIf the above are all true, I'd suggest using the
basic_string
who'schar_type
matches the size of the primitive contained in yourvector
. You should include astatic_assert
in your code to validate these sizes stay consistent:With this holding true you can just do:
For more information on the differences between
string
andvector
you can look here: https://stackoverflow.com/a/35558008/2642059For a live example of this code you can look here: http://ideone.com/7Iww3I
I prefer one that is already mentioned:
But if you use C++11, there is one more generic way:
Also, not part of a question, but it is advisable to use
reserve
before appending for better performance. And if you are concatenating vector with itself, without reserving it fails, so you always shouldreserve
.So basically what you need: