I’ve recently started using new C++11 features like lambda expressions to make my code easier to read.
In this example, I want to generate a vector of numbers [0 to n] sorted randomly. I have some code similar to the following
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
void _generateRandomIndices(vector<unsigned int> & indices,
const unsigned int & n) {
indices.clear();
unsigned int i = 0;
generate_n(back_inserter(indices), n , [&i] ()-> unsigned int{
return i++;
} );
random_shuffle(indices.begin(), indices.end());
}
However, using g++ 4.6 on windows(with the -std=c++0x flag) threw me the following error:
no matching function for call to 'generate_n(std::back_insert_iterator<std::vector<unsigned int> >, const unsigned int&, _generateRandomIndices(std::vector<unsigned int>&, const unsigned int&)::<lambda()>)'
What is the right way to use a lambda expression in this case ?
Sounds like you are missing an
#include <algorithm>, since GCC 4.5.1 aswell as MSVC10 compile the following code without error: