我如何连接两个std::向量?
当前回答
在c++ 11中,我更喜欢将向量b附加到a:
std::move(b.begin(), b.end(), std::back_inserter(a));
当a和b不重叠时,b不会再被用到。
这是std::move from <algorithm>,而不是通常的std::move from <utility>。
其他回答
我将使用插入函数,类似于:
vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
这个解决方案可能有点复杂,但助推范围也有一些其他的好处。
#include <iostream>
#include <vector>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
boost::copy(b, std::back_inserter(a));
for (auto& iter : a) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
通常我们的目的是将向量a和b结合起来只是在上面做一些运算。在本例中,有一个可笑的简单连接函数。
#include <iostream>
#include <vector>
#include <boost/range/join.hpp>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
std::vector<int> c = { 7,8,9 };
// Just creates an iterator
for (auto& iter : boost::join(a, boost::join(b, c))) {
std::cout << iter << " ";
}
std::cout << "\n";
// Can also be used to create a copy
std::vector<int> d;
boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));
for (auto& iter : d) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
对于较大的向量,这可能是一个优势,因为不需要复制。它还可以用于轻松地将泛化复制到多个容器。
出于某种原因,没有像boost::join(a,b,c)这样的东西,这可能是合理的。
试着创建两个向量,把第二个向量和第一个向量相加, 代码:
std::vector<int> v1{1,2,3};
std::vector<int> v2{4,5};
for(int i = 0; i<v2.size();i++)
{
v1.push_back(v2[i]);
}
v1:1 2 3。
描述:
当i int不是v2大小时,回推元素,在v1向量中索引i。
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));
vector1.insert( vector1.end(), vector2.begin(), vector2.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++能让你免费获得性能吗?
- 一门语言是如何自我扩展的?