简体   繁体   中英

Can't push_back into vector - gives no overload error

I looked at several past questions (eg 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.

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); }
                                                         ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM