c++ - 反向打印任何 vector 的通用函数,编译器错误

标签 c++ stl iterator stdvector

<分区>

现在我正在学习模板和 vector 。我做了一个简单的函数来打印一个 vector ,该 vector 具有从 .back() 元素到 .front() 元素的任何数据类型的元素。

template <typename Type>
void printVectorReverse(const vector<Type>& stuff)
{
    for (auto it = stuff.crbegin(); it != crend(); ++it) {
        cout << *it << endl;
    }
}

我正在编译程序,但出现错误:

$ g++ -std=c++11 template_functions.cpp 
template_functions.cpp: In function ‘void printVectorReverse(const std::vector<Type>&)’:
template_functions.cpp:66:49: error: there are no arguments to ‘crend’ that depend on a template parameter, so a declaration of ‘crend’ must be available [-fpermissive]
     for (auto it = stuff.crbegin(); it != crend(); ++it) {
                                                 ^
template_functions.cpp:66:49: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

我在这里没有看到语法错误。函数上方有一个模板类型名声明。 vector 是 const 通过引用传递以避免复制它,因此函数不会无意中更改 vector 。我有一个常量反向迭代器指向 .back() 元素。然后我取消对迭代器的引用并递增它,直到它到达 vector 的反向端并结束。我正在使用 auto,因为 vector 可以有任何数据类型。

顺便说一下这个错误怎么读?这是什么意思?请不要太苛刻,因为这对我来说是一个相对较新的话题。我真的很想学习模板和序列容器。

最佳答案

错误是这样读的:

error: there are no arguments to ‘crend’ that depend on a template parameter, so a [function] declaration of ‘crend’ must be available [-fpermissive]

这意味着编译器不知道 crend() 是什么。它怀疑它是一个函数,但找不到它的声明。

你打错了;你需要有 stuff.crend():

for (auto it = stuff.crbegin(); it != stuff.crend(); ++it)

关于c++ - 反向打印任何 vector 的通用函数,编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51511645/

相关文章:

javascript - 使用解构或 forEach 进行减少 - 迭代和 Airbnb JavaScript 风格指南

c++ - GCC 7,aligned_storage 和 "dereferencing type-punned pointer will break strict-aliasing rules"

C++ For 循环和多维数组

c++ - 从包含的类调用容器类中定义的回调函数的推荐方法是什么?

c++ - 为什么在 STL 中允许未定义的行为?

python - 在没有内存泄漏的情况下在 Python 中公开 STL 结构

java - 即使检查是否为空,.iterator() 也会产生空指针异常

java - 在没有接口(interface)调用或反射调用的情况下使用类加载器创建的对象?

c++ - 针对 C++11 的 boost::any typeid 优化

rust - 在 Rust 中定义采用迭代器而不消耗的函数的惯用方法是什么?