c++ - 容器模板,错误在哪里?

标签 c++ templates vector containers

我有以下代码,我想为容器大小制作一个模板(例如 vector 、数组、列表等) 主要是我定义了一个 vector ,并从模板中调用了 mysize 函数,但我得到了一个错误:“参见 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);

}

最佳答案

无法推导出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;
}

或者:

template <typename I>
std::size_t mysize(I first, I last)
{
    std::size_t it = 0;
    while (first != last) {
        ++first;
        ++it;
    }
    return it;
}

或者:

template <typename I>
std::size_t mysize(I first, I last)
{
    return std::distance(first, last);
}

关于c++ - 容器模板,错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859134/

相关文章:

c++ - 您可以使用 CRTP 和以接口(interface)作为参数的函数吗?

c++ - 以基类为模板参数继承基构造函数(MSVC)

c++ - 将 char* 转换为 std::vector

c++ - 如何在 C++ 中跟踪 BFS 深度

c++ - 连接 Qt 应用程序中的 GUI 和计算

C++从编译时多态性中隐藏模板习语

c - 将 vector A 按逆序转置为 B

c++ - Vector如何在特定位置调用复制构造函数?

c++ - 如何在 std::list 中使用递归?

c++ - 使用 while/do-while 循环进行数组元素设置