How can I fix this error `conversion from const_iterator to non-scalar type`?

10,014

You are passing in a const Gen<T> to operator<<. This means when you call g.array.begin() you are invoking the const overload of begin, which returns a const_iterator:

const_iterator begin() const noexcept;

and then you try to assign it to a vector<T>::iterator, which causes the compiler error. You can fix this like this:

auto it = g.array.begin()

which tells the compiler to deduce the correct type for it.

Share:
10,014
AskMath
Author by

AskMath

Updated on June 04, 2022

Comments

  • AskMath
    AskMath almost 2 years

    can someone explain what is the mention of this error:

    conversion from 'std::vector<int, std::allocator<int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >}' to non-scalar type 'std::vector<int, std::allocator<int> >::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >}' requested

    given the following class:

    #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;
    }
    

    how can I fix that?

  • AskMath
    AskMath almost 6 years
    Can I convert const_iterator to iterator by some way?
  • zdan
    zdan almost 6 years
    No. why would you want to?