获取"子"向量和"连接"向量

Grab a "sub"-vector and "concatenate" vectors

本文关键字:向量 连接 获取      更新时间:2023-10-16

所以我正在写一个并行程序(boost.mpi),我想传递一个向量的片段(如std::vector),这些片段可以组装成一个完整的向量。

为了做到这一点,我想能够做两件事:

  1. 抓住一个向量的一部分——比如说一个向量有800个元素,那么制作一个包含200-299个元素(或由2个int变量定义的任意索引)的子向量的最佳方法是什么?

  2. 我想创建一个运算符,它将允许我将向量相加,以创建一个新的、更长的向量。基本上,我想要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之类的东西。