public
Created

  • Download Gist
boost_lambda.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
 
using namespace std;
using namespace boost::lambda;
 
int main(int argc, const char *argv[])
{
int a[] = {6,5,3,12,1,-7,13,20,16,0};
int index[] = {0,1,2,3,4,5,6,7,8,9};
vector<int> v(a, a+10);
 
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")), cout << endl;
copy(index, index+10, ostream_iterator<int>(cout, " ")), cout << endl;
 
#if 0
My problem is here. My build environment is: Ubuntu 10.04 64-bit server (kernel 2.6.32), gcc 4.4.3
I understand there's lambda function in C++11. I'd just like to try boost::lambda.
#endif
#if 1
// This is OK
sort(v.begin(), v.end());
#elif 1
// 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]);
#elif 1
// However, they overload operator+ and operator*
sort(index,index+10, *(a+_1) < *(a+_2));
#elif 1
// I'd like to sort the indexes according to the vector, but compiler cannot resolve the type of `vector<int>::at'
// The message: ... error: no matching function for call to ‘bind(<unresolved overloaded function type>, ...
sort(index,index+10, bind(&(vector<int>::at), &v, _1) < bind(&(vector<int>::at), &v, _2));
#elif 1
// After searching on the web, I found I have to specify the overloaded method type, but compiler still says it cannot resolve the type
// The message: ... error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘const int (*)(size_t)’ ...
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));
#elif 1
// I tried to get the version of vector<int>::at I want, but the conversion seems to be failed
// The message: ... error: no matches converting function ‘at’ to type ‘const int& (*)(size_t)’ ...
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));
#elif 1
// Great! I didn't use the correct type to define the vector_int_at. Now it's availible.
vector<int>::const_reference (vector<int>::*vector_int_at)(vector<int>::size_type) const = &vector<int>::at;
sort(index,index+10, bind(vector_int_at, &v, _1) < bind(vector_int_at, &v, _2));
#elif 1
// A C++11 lambda solution is more clear
sort(index, index+10, [&v](int i, int j){ return v[i] < v[j]; });
#endif
 
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")), cout << endl;
copy(index, index+10, ostream_iterator<int>(cout, " ")), cout << endl;
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.