Concatenate empty vector with two other vectors
Mar 11, 2015 at 4:00pm UTC
I am trying to concatenate two std::vectors together.
I'm using
http://stackoverflow.com/a/201729 as a basis for my code.
1 2 3 4 5 6 7 8 9 10 11
Foo operator +(const Foo& lhs, const Foo& rhs)
{
Foo ret; // creates object initally with empty m_vector.
// Concatenate m_vector
ret.m_vector.insert(ret.m_vector.end(),
lhs.m_vector.begin(),
lhs.m_vector.end() );
ret.m_vector.insert(ret.m_vector.end(),
rhs.m_vector.begin(),
rhs.m_vector.end() );
Is there a way to do this efficiently with just one insert call since I know that
ret initially has an empty vector? I should probably learn more about iterators, so sorry if this is an obvious question.
Or would it be better to have a constructor that copies
lhs 's m_vector into ret's m_vector, and then call insert() to insert the
rhs vector?
Mar 11, 2015 at 5:21pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <vector>
template <typename T>
std::vector<T> addVec(const std::vector<T>& v1, const std::vector<T>& v2)
{
std::vector<T> vec;
vec = v1;
vec.insert(vec.end(), v2.begin(), v2.end());
return vec;
}
int main(){
std::vector<int > v1{1,2,3,4,5};
std::vector<int > v2{6,7,8};
std::vector<int > v3;
v3 = addVec(v1, v2);
for (auto x:v3){
std::cout << x << " " ;
}
return 0;
}
Mar 11, 2015 at 5:28pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
#include <vector>
template <typename T>
std::vector<T> operator +(const std::vector<T>& v1, const std::vector<T>& v2)
{
std::vector<T> vec;
vec = v1;
vec.insert(vec.end(), v2.begin(), v2.end());
return vec;
}
int main(){
std::vector<int > v1{1,2,3,4,5};
std::vector<int > v2{6,7,8};
std::vector<int > v3;
v3 = v1+v2;
for (auto x:v3){
std::cout << x << " " ;
}
return 0;
}
EDIT:
1 2 3 4 5 6
template <typename T>
std::vector<T> operator +( std::vector<T> v1, const std::vector<T>& v2)
{
v1.insert(v1.end(), v2.begin(), v2.end());
return v1;
}
Last edited on Mar 11, 2015 at 5:32pm UTC
Mar 11, 2015 at 7:10pm UTC
Ah right... you just copy construct it and then insert the right-hand side. Thanks for the example.
Topic archived. No new replies allowed.