无法在C++函数中返回std :: vector,编译错误

Thi*_*aes 2 c++ stl vector

我在尝试编译下面的代码片段时遇到以下错误(使用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> >&)’
Run Code Online (Sandbox Code Playgroud)

这是生成错误的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

真正的代码将取消注释两个注释行,但即使是注释的示例也会给我错误.我究竟做错了什么?

Arm*_*yan 6

vector<pos> sorted_matches();
Run Code Online (Sandbox Code Playgroud)

这声明了一个不带任何东西并返回一个的函数vector<pos>.这被称为最令人烦恼的解析.如果你不相信我,想象一下变量是命名f而不是sorted_matches:

vector<pos> f();
Run Code Online (Sandbox Code Playgroud)

看起来像一个功能,不是吗?

使用它来定义默认构造的对象:

vector<pos> sorted_matches;
return sorted_matches;
Run Code Online (Sandbox Code Playgroud)