2

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?

4
  • Even with the first line uncommented, you're not posting your real code. Please post an actual, minimal, self-contained example that exhibits your problem. Commented May 7, 2012 at 12:51
  • @Xeo: The current code certainly has the usual vexing parse misunderstanding, but I have a feeling that the original code the OP had in mind was returning a reference to a vector. Commented May 7, 2012 at 12:52
  • Oh, and I just noticed another problem: You're returning sort_matches, not sorted_matches. That would be the actual problem that also wouldn't allow the commented parts to compile. My bad for the hasty close vote. Voted to reopen. :P Commented May 7, 2012 at 12:53
  • You are returning the name of the function itself, i.e. a function pointer. That doesn't make sense. Commented May 7, 2012 at 12:53

1 Answer 1

6
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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.