c++ - 反向打印任何向量的通用函数,编译器错误
问题描述
现在我正在学习模板和向量。我做了一个简单的函数来打印一个向量,该向量具有从.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
,因为向量可以有任何数据类型。
顺便说一句,我该如何阅读这个错误?这是什么意思?请不要那么苛刻,因为这对我来说是一个相对较新的话题。我真的很想学习模板和序列容器。
解决方案
错误是这样读取的:
错误:“cred”没有依赖于模板参数的参数,所以[功能]'cred' 的声明必须可用[-fpermissive]
这意味着编译器不知道是什么crend()
。它怀疑它是一个函数,但找不到它的声明。
你打错了; 你需要有stuff.crend()
:
for (auto it = stuff.crbegin(); it != stuff.crend(); ++it)
推荐阅读
- gojs - 如何使文本块中的文本显示在同一空间中的所有元素上方(前景)
- excel - vba循环文本到列日期格式
- r - 从 2019 年 10 月 1 日到 2019 年 12 月 30 日,在 R 中创建时间序列,不包括周末或节假日
- python - django如何从函数中返回classBasedView
- python - 弹出时如何在组合框上启用写入
- owasp - 在白名单操作上使用自定义 REQUEST_HEADER
- .net-core - 当分区未知(但行键是)时检索结果
- python - 如何使用 Numpy 创建给定无符号整数的二进制数字数组?
- typescript - 从接口中删除 TypeScript 可索引类型
- javascript - 添加事件监听器 | 拦截方法调用