我如何连接两个std::向量?
当前回答
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
其他回答
std::vector<int> first;
std::vector<int> second;
first.insert(first.end(), second.begin(), second.end());
或者你可以用:
std::copy(source.begin(), source.end(), std::back_inserter(destination));
如果两个向量不包含完全相同类型的内容,则此模式非常有用,因为您可以使用某些内容而不是std::back_inserter来从一种类型转换为另一种类型。
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
你可以为+操作符准备自己的模板:
template <typename T>
inline T operator+(const T & a, const T & b)
{
T res = a;
res.insert(res.end(), b.begin(), b.end());
return res;
}
接下来,使用+:
vector<int> a{1, 2, 3, 4};
vector<int> b{5, 6, 7, 8};
for (auto x: a + b)
cout << x << " ";
cout << endl;
这个例子给出了输出:
1 2 3 4 5 6 7 8
我将使用插入函数,类似于:
vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?
- 现代c++能让你免费获得性能吗?
- 一门语言是如何自我扩展的?