第一部分可以通过以下矢量构造来实现:
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
。
对于第一部分,有一个构造函数需要范围。不知道是否有更好的方法,但'矢量 vSub(vMain.begin()+ 200,vMain.begin()+ 299);'应该工作。 –
chris
2012-03-30 18:25:52
啊,当然可以。我忘记了那个构造函数。我认为这应该很好。谢谢 – Kyle 2012-03-30 18:28:02