简体   繁体   English

无法push_back到向量-没有重载错误

[英]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>> 没有重载函数“ std :: vector <_Tp,_Alloc> :: push_back [with _Tp = int,_Alloc = std :: allocator <int>]”的实例与参数列表和对象匹配(该对象具有防止使用匹配)-参数类型为:(int)-对象类型为: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. 注意:我不会将int推入sorted_edges我正在测试以查看是否错误地创建了边缘结构,或者是否错误地使用了向量。

Regarding the error you get: 关于错误您得到:

... the object has type qualifiers that prevent a match -- argument types are: (int) -- object type is: const std::vector. ...对象具有防止匹配的类型限定符 -参数类型为:(int)-对象类型为: 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. 首先,您应该检查发布的代码是否正确-您声明它是非常量,但错误明确指出否则,尽管您可能会将其作为const ref传递给函数-这是一种可能。

In any case, you cannot push_back into a const vector since it's, well, const :-) 无论如何,您不能将push_back推入const vector因为它是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. 当您使用-DXYZZY=编译(这样XYZZY有效消失)时,它可以编译。 With -DXYZZY=const however, you get an error: 但是,如果使用-DXYZZY=const ,则会出现错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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