代码之家  ›  专栏  ›  技术社区  ›  Galaxy

用于反向打印任何矢量的泛型函数,编译器错误[关闭]

  •  1
  • Galaxy  · 技术社区  · 6 年前

    现在我正在学习模板和向量。我制作了一个简单的函数来打印一个向量,其中包含来自 .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 传递引用以避免复制它,这样函数就不会无意中更改向量。我有一个常量反向迭代器指向 后退() 元素。然后我取消对迭代器的引用,并将其递增,直到它到达向量的反端,然后 最后的落差 . 我正在使用 auto 因为向量可以有任何数据类型。

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

    1 回复  |  直到 6 年前
        1
  •  4
  •   Tas    6 年前

    错误如下:

    错误:没有依赖模板参数的crend参数, 所以A [函数] 必须提供CREND声明 [fimistou]

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

    你犯了错,你需要 stuff.crend() :

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