模板函数采用std :: vector或std :: array [英] Template function taking a std::vector or std::array
本文介绍了模板函数采用std :: vector或std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,当前可以接受2个向量,这些向量可以包含任何简单的旧数据...
I have a function that currently accepts 2 vectors that can contain any plain old data ...
template <class T>
void addData(const vector<T>& yData, vector<T> xData)
{ .. }
问题:
- 考虑到这些容器采用不同数量的模板参数,是否可以将其修改为两个
std::array
或两个std::vector
甚至是它们的组合?
- Would it be possible to modify it to take two
std::array
or twostd::vector
, or even a combination thereof, given that these containers take a different number of template arguments?
推荐答案
为什么不只使用它,它可以与任何使用随机访问迭代器的容器一起使用,包括普通的旧数组.如果可以使用迭代代替索引,那么也可以消除随机访问的要求.
Why not just use this, which works with any container using random-access iterators, including plain old arrays. If you can use iteration instead of indexing, you can do away with the random-access requirement as well.
template <typename Cnt1, typename Cnt2>
void addData(const Cnt1& yData, Cnt2 xData) // is pass-by-value intended?
{
using std::begin;
using std::end;
typedef decltype(*begin(yData)) T;
const auto sizeY = end(yData) - begin(yData);
const auto sizeX = end(xData) - begin(xData);
// ...
}
C ++ 03版本(不支持普通的旧数组):
C++03 version (doesn't support plain old arrays):
template <typename Cnt1, typename Cnt2>
void addData(const Cnt1& yData, Cnt2 xData) // is pass-by-value intended?
{
typedef Cnt1::value_type T;
const size_t sizeY = yData.end() - yData.begin();
const size_t sizeX = xData.end() - xData.begin();
// ...
}
这篇关于模板函数采用std :: vector或std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文