繁体   English   中英

抓取“子”向量和“连接”向量

[英]Grab a “sub”-vector and “concatenate” vectors

因此,我正在编写一个并行程序(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类的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM