2012-03-30 42 views
0

所以我写了一个并行程序(boost.mpi),我想传递一个向量(如在std :: vector中)一个完整的矢量。抓住一个“子”向量和“连接”向量

为了做到这一点,我希望能够做两件事情:

  1. 抢一块的载体 - 即说向量有800元,什么是然后做出最好的办法一个包含元素200-299(或由2个int变量定义的任意索引)的子向量?

  2. 我想创建一个运算符,它允许我将矢量添加到一起以创建一个新的更长的矢量。基本上,我想要std :: plus()(可以连接字符串)给出的相同功能,但是对于向量。我需要能够将此运算符作为二元运算符(它需要与std :: plus())具有相同的类型。

任何与此有关的帮助将不胜感激。

+0

对于第一部分,有一个构造函数需要范围。不知道是否有更好的方法,但'矢量 vSub(vMain.begin()+ 200,vMain.begin()+ 299);'应该工作。 – chris 2012-03-30 18:25:52

+0

啊,当然可以。我忘记了那个构造函数。我认为这应该很好。谢谢 – Kyle 2012-03-30 18:28:02

回答

0

第一部分可以通过以下矢量构造来实现:

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

+0

我认为这应该工作。我现在唯一需要知道的是如何将“+”运算符作为运算符来传递? – Kyle 2012-03-30 20:09:57

+0

我已经使代码中的新部分脱颖而出,但在编写代码时这样做似乎很糟糕。你可能想看看有没有比这更好的东西。 – chris 2012-03-30 20:50:20

+0

IIRC,你需要将'ret.end()'包装在'std :: back_inserter'内,否则可能会发生UB。 – moshbear 2012-03-30 20:57:44