泛型函数反向打印任何矢量,编译器出错

Generic function to print any vector in reverse, compiler error

本文关键字:编译器 出错 任何矢 打印 函数 泛型      更新时间:2023-10-16

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

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

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

错误如下所示:

错误:"crend"没有依赖于模板参数的参数,因此必须有<function]>声明"cred">[-fpermission]

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

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

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