0
votes

I looked at several past questions (e.g. no instance of overloaded function) but these were not relevant. I understand that there is a type mismatch but I don't understand why, with my setup, I'm getting this error.

I'm getting this error:

no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back [with _Tp=int, _Alloc=std::allocator<int>]" matches the argument list and object (the object has type qualifiers that prevent a match) -- argument types are: (int) -- object type is: const std::vector<int, std::allocator<int>>

This is the code:

std::vector<int> sorted_edges;

...

//let's sort the edges 
for(int i = 0; i < num_nodes; ++i){
    for(int j = 0; j < num_nodes; ++j){
        if(graph[i][j] != INF){
            sorted_edges.push_back(i);
        }
    } 
}

Note: I'm not going to push an int into sorted_edges - I was testing to see whether I was incorrectly creating my edge struct or whether I was using vectors incorrectly.

1
Is the vector a member of a class and the code you've shown in a const member function? A minimal reproducible example would allow for a real answer that takes your real code into account.Retired Ninja

1 Answers

5
votes

Regarding the error you get:

... the object has type qualifiers that prevent a match -- argument types are: (int) -- object type is: const std::vector.

First, you should check the code you've posted is correct - you state it's a non-const but the error clearly states otherwise, though you may be passing it to a function as a const ref - that's one possibility.

In any case, you cannot push_back into a const vector since it's, well, const :-)

You can see that with the following code:

#include <vector>
int main() { XYZZY std::vector<int> x; x.push_back(42); }

When you compile with -DXYZZY= (so the XYZZY effectively disappears), it compiles okay. With -DXYZZY=const however, you get an error:

qq.cpp: In function ‘int main()’:
qq.cpp:2:54: error: passing ‘const std::vector<int>’ as ‘this’
    argument discards qualifiers [-fpermissive]
    int main() { XYZZY std::vector<int> x; x.push_back(42); }
                                                         ^