Question

The complete code is on https://gist.github.com/1341623

I'd like to sort an index array (or vector) for another vector, such that the array is ordered by the index of the other vector. However, the type of vector::at cannot be resolved.

I did a try as follows:

This is OK

sort(v.begin(), v.end());

I'd like to sort the indexes according to the array, but placeholders do not overload operator[]

sort(index,index+10, a[_1] < a[_2]);

However, they overload operator+ and operator*

sort(index,index+10, *(a+_1) < *(a+_2));

I'd like to sort the indexes according to the vector, but compiler cannot resolve the type of `vector::at'.

sort(index,index+10,
  bind(&(vector<int>::at), &v, _1) < bind(&(vector<int>::at), &v, _2));
// error: no matching function for call
// to ‘bind(<unresolved overloaded function type>, ...

After searching on the web, I found I have to specify the overloaded method type, but compiler still says it cannot resolve the type.

sort(index,index+10,
   bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _1)
 < bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _2));
// error: invalid static_cast from type ‘<unresolved overloaded function type>’
// to type ‘const int (*)(size_t)’ ...

I tried to get the version of vector::at I want, but the conversion seems to be failed.

vector<int>::const_reference (*vector_int_at)(vector<int>::size_type)(vector<int>::at);
sort(index,index+10,
  bind(&vector_int_at, &v, _1) < bind(&vector_int_at, &v, _2));
// error: no matches converting function ‘at’ to type ‘const int& (*)(size_t)’ ...

What can I do for this problem? Or I misunderstand something?

Was it helpful?

Solution

Remember that pointers to member functions and pointers to free functions have different types. Try: vector<int>::const_reference (vector<int>::*vector_int_at)(vector<int>::size_type) const = &vector<int>::at;

OTHER TIPS

I usually just declare a forwarding function to avoid the various cans of worm associated with this sort of thing:

int vector_at(vector<int> const * v, size_t index) { return v->at(index); }

...

sort(index, index+10, bind(vector_at, &v, _1) < bind(vector_at, &v, _2));

Any reason why you do not use a lambda?

sort(index, index+10, [&a](int i, int j) { return a[i] < a[j]; });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top