Thiago Moraes
Thiago Moraes

Reputation: 617

Can't return std::vector in a C++ function, compiling error

I'm having the following error while trying to compile the snippet below (using 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> >&)’

This is the code that generates the error:

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

The real code would have the two commented lines uncommented, but even the commented example gives me the error. What am I doing wrong?

Upvotes: 2

Views: 1276

Answers (1)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

vector<pos> sorted_matches();

this declares a function that takes nothing and returns a vector<pos>. This is known as the most vexing parse. If you don't believe me, imagine the variable is named f instead of sorted_matches:

vector<pos> f();

Looks like a function, doesn't it?

Use this to define a default-constructed object:

vector<pos> sorted_matches;
return sorted_matches;

Upvotes: 6

Related Questions