2012-03-30 35 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