c++ - 为什么第二个变量作为引用和常量传递

标签 c++

为什么 first 不作为引用和 const 传递?

template <typename Iterator>
    int distance(Iterator first, const Iterator & last) {
    int count;
    for ( ; first != last; first++)
        count++;
    return count;
}

最佳答案

它不能是 const,因为它在函数内部递增,而且它不是通过引用传递的,因为这样做对调用者来说可能没有意义。

此外,如果它是非常量引用,则不可能使用临时引用。例如,您不能这样做:

std::vector<int> v{ 1, 2, 3, 4 };
auto distance = std::distance(v.begin(), v.end());

关于c++ - 为什么第二个变量作为引用和常量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11954493/

相关文章:

c++ - 共享库的 TX 文件扩展名?

c++ - C++ 中的函数指针转换

c++ - 函数 'strlen' 无法解析 - Eclipse cpp

c++ - 如何有效地将 vector<pair<int,int>> 转换为 multimap<int,int>?

c++ - uWebSockets (C++) : secure wss server

c++ - 多态性和函数重载?

c++ - C结构和C++结构

c++ - 使用 Visual C++ 形式读取文件的行为与在 C 程序中读取的行为不同

c++ - windows上qt连接oracle数据库

c++ - 从不兼容的指针类型初始化 - 现在怎么办?