首页 > 解决方案 > 反向打印任何向量的通用函数,编译器错误

问题描述

现在我正在学习模板和向量。我做了一个简单的函数来打印一个向量,该向量具有从.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)

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

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

标签: c++stliteratorstdvector

解决方案


错误是这样读取的:

错误:“cred”没有依赖于模板参数的参数,所以[功能]'cred' 的声明必须可用[-fpermissive]

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

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

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

推荐阅读