0

だから私は並列プログラム(boost.mpi)を書いていて、ベクトル全体を作成するためにアセンブルできるベクトルの断片(std :: vectorのように)を渡したいと思っています。

これを行うために、私は2つのことを実行できるようにしたいと思います。

  1. ベクトルの一部を取得します。つまり、ベクトルに800個の要素がある場合、要素200〜299(または2つのint変数で定義される任意のインデックス)を含むサブベクトルを作成するための最良の方法は何ですか。

  2. ベクトルを一緒に追加して、新しい、より長いベクトルを作成できる演算子を作成したいと思います。基本的に、std :: plus()(文字列を連結できます)が提供するのと同じ機能が必要ですが、ベクトル用です。この演算子を二項演算子として渡すことができる必要があります(std :: plus()と同じ型である必要があります)。

これで少しでも助けていただければ幸いです。

4

1 に答える 1

0

最初の部分は、次のベクター コンストラクターを使用して実現できます。

template <class InputIterator>
vector( InputIterator first, InputIterator last, 
        const Allocator& alloc = Allocator() );

2 番目の部分は を使用して実現できますが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.

于 2012-03-30T19:18:55.530 に答える