如何解决此错误“从const_iterator转换为非标量类型”?

Ask*_*ath 3 c++ iterator vector c++11

有人可以解释该错误的含义:

从'std :: vector <int,std :: allocator <int>> :: const_iterator {aka __gnu_cxx :: __ normal_iterator <const int *,std :: vector <int,std :: allocator <int> >>}'转换到非标量类型'std :: vector <int,std :: allocator <int>> :: iterator {aka __gnu_cxx :: __ normal_iterator <int *,std :: vector <int,std :: allocator <int>>> }'请求

给定以下类别:

#include <vector>
#include <iostream>

using std::vector;
using std::ostream;

template<class T>
class Gen {
    vector<T> array;
public:
    explicit Gen(int size);
    template<class S>
    friend ostream& operator<<(ostream& os, const Gen<S>& g);
};

template<class T>
Gen<T>::Gen(int size) {
    for (int i = 0; i < size; i++) {
        this->array.push_back(T());
    }
}

template<class T>
ostream& operator<<(ostream& os, const Gen<T>& g) {
    for (typename vector<T>::iterator it = g.array.begin(); it != g.array.end();
            it++) { // ****** error ********
        os << *it << " ";
    }
    return os;
}

int main() {
    Gen<int> g(3);
    std::cout << g << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

zda*_*dan 5

您正在将传递const Gen<T>operator<<。这意味着在调用时,g.array.begin()您将调用begin的const重载,这将返回const_iterator

const_iterator begin() const noexcept;
Run Code Online (Sandbox Code Playgroud)

然后尝试将其分配给vector<T>::iterator,这会导致编译器错误。您可以这样解决:

auto it = g.array.begin()
Run Code Online (Sandbox Code Playgroud)

告诉编译器推断的正确类型it