0 c++ containers templates vector
我有以下代码,我想为容器大小制作一个模板(例如矢量,数组,列表等)在主要我定义一个向量,我从模板调用mysize函数,但我得到一个错误:"看到声明of mysize".有人可以帮忙吗?
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
template <typename I, typename Op>
Op mysize(I first, I last)
{
auto it = 0;
while (first != last) {
++first;
it += 1;
}
return it;
}
void main()
{
vector<int> v = {1,2,3,4,5,6,7,8};
auto _begin = v.begin();
auto _end = v.end();
auto result = mysize(_begin, _end);
}
Run Code Online (Sandbox Code Playgroud)
该Op类型无法推断.
这应该工作:
template <typename I, typename Op = std::size_t>
Op mysize(I first, I last)
{
auto it = 0;
while (first != last) {
++first;
it += 1;
}
return it;
}
Run Code Online (Sandbox Code Playgroud)
要么:
template <typename I>
std::size_t mysize(I first, I last)
{
std::size_t it = 0;
while (first != last) {
++first;
++it;
}
return it;
}
Run Code Online (Sandbox Code Playgroud)
要么:
template <typename I>
std::size_t mysize(I first, I last)
{
return std::distance(first, last);
}
Run Code Online (Sandbox Code Playgroud)