获取"子"向量和"连接"向量
Grab a "sub"-vector and "concatenate" vectors
所以我正在写一个并行程序(boost.mpi),我想传递一个向量的片段(如std::vector),这些片段可以组装成一个完整的向量。
为了做到这一点,我想能够做两件事:
-
抓住一个向量的一部分——比如说一个向量有800个元素,那么制作一个包含200-299个元素(或由2个int变量定义的任意索引)的子向量的最佳方法是什么?
-
我想创建一个运算符,它将允许我将向量相加,以创建一个新的、更长的向量。基本上,我想要std::plus()(可以连接字符串)提供的相同功能,但对于向量。我需要能够将此运算符作为二进制运算符传递(它需要具有与std::plus()相同的类型)。
如有任何帮助,我们将不胜感激。
第一部分可以通过使用以下向量构造函数来实现:
template <class InputIterator>
vector( InputIterator first, InputIterator last,
const Allocator& alloc = Allocator() );
第二部分可以使用vector::insert
来实现,但可能有更好的方法。我给了下面每一个的样本。
#include <vector>
using std::vector;
template <typename T>
vector<T> operator+ (const vector<T> &lhs, const vector<T> &rhs)
{
vector<T> ret (lhs);
ret.insert (ret.end(), rhs.begin(), rhs.end());
return ret;
}
/// new //create a structure like std::plus that works for our needs, could probably turn vector into another template argument to allow for other templated classes
template <typename T>
struct Plus
{
vector<T> operator() (const vector<T> &lhs, const vector<T> &rhs)
{
return lhs + rhs;
}
};
/// end new
#include <iostream>
using std::cout;
/// new
#include <numeric>
using std::accumulate;
/// end new
template <typename T>
void print (const vector<T> &v)
{
for (const T &i : v)
cout << i << ' ';
cout << 'n';
}
int main()
{
vector<int> vMain {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //syntax only available in C++11
vector<int> vSub (vMain.begin() + 3, vMain.begin() + 6); //vMain[0+3]=4, vMain[0+6]=7
vector<int> vCat = vMain + vSub;
/// new
vector<vector<int>> vAdd {vMain, vMain}; //create vector of vector of int holding two vMains
/// end new
print (vMain);
print (vSub);
print (vCat);
/// new //accumulate the vectors in vAdd, calling vMain + vMain, starting with an empty vector of ints to hold the result
vector<int> res = accumulate (vAdd.begin(), vAdd.end(), (vector<int>)(0));//, Plus<int>());
print (res); //print accumulated result
/// end new
}
输出:
1 2 3 4 5 6 7 8 9 10
4 5 6
1 2 3 4 5 6 7 8 9 10 4 5 6
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
编辑:我真的对我是如何做到这一点有一种不好的感觉,但我已经更新了代码来处理std::accumulate
之类的东西。
相关文章:
- 用于连接向量的 Constexpr 函数
- C++将两个不同类型的向量的属性连接到新的向量中
- 以零字节作为定界符/终端的字节加入(连接)字符串向量
- 交叉连接 2 个向量的元素以产生第三个
- C++线程的向量在连接时随机崩溃
- 将两个向量与另一个向量连接起来
- 有没有办法像python:np.concatenate([x,y,z],axis=1)中那样沿着列连接三个二维向量C++
- Swig - 结构的 c++ 向量以及如何连接它们
- <T> 在使用运算符+ 连接两个向量之前从类型向量中删除索引
- 有没有办法简单地连接多个向量
- 尝试保存到成员向量的连接-一次只保存一个
- 如何连接/合并向量
- 如何使用 boost 连接 c++ 中的字符串向量
- std::bad_alloc连接两个向量时
- 如何连接向量的两个元素
- 对百万或十亿个 STL 向量进行排序和连接的最快方法
- 在转换一个向量的元素时,连接两个向量的最佳方式是什么
- 如何连接多个std::向量
- 将带有时间戳的向量整数连接为C++中的字符串
- 在c++中不使用STL或向量连接两个字符串数组