[英]Can't return std::vector in a C++ function, compiling error
我在尝试编译以下代码段时遇到以下错误(使用g ++):
error: invalid initialization of non-const reference of type
‘std::vector<pos,std::allocator<pos> >&’ from a temporary of
type ‘std::vector<pos, std::allocator<pos> >&
(*)(std::vector<pos, std::allocator<pos> >&)’
这是生成错误的代码:
struct pos{
int start;
int end;
int distance;
int size;
};
bool compare_pos(pos a, pos b)
{
if (a.distance != b.distance)
return (a.distance < b.distance);
else
return (a.size < b.size);
}
vector<pos> sort_matches(vector<pos>& matches)
{
//vector<pos> sorted_matches(matches);
vector<pos> sorted_matches();
//sort(sorted_matches.begin(), sorted_matches.end(), compare_pos);
return sort_matches;
}
实际的代码将没有注释两行注释,但是即使注释的示例也给了我错误。 我究竟做错了什么?
vector<pos> sorted_matches();
这声明了一个不做任何事情并返回vector<pos>
的函数。 这被称为最烦人的解析 。 如果您不相信我,可以想象该变量名为f
而不是sorted_matches
:
vector<pos> f();
看起来像一个函数,不是吗?
使用此定义默认构造的对象:
vector<pos> sorted_matches;
return sorted_matches;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.