Bonita Montero
unread,Nov 19, 2023, 6:04:25 AM11/19/23You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
I was interested in whether my C++ implementations pass the lambda you
supply with std::sort through the recursion of sort by coping. libstdc++
(g++) and libc++ (clang++) copy the lambda at each recursion level. MSVC
stores the lambda only once.
#include <iostream>
#include <vector>
#include <random>
#include <unordered_map>
#include <climits>
#include <algorithm>
using namespace std;
int main( int argc, char **argv )
{
mt19937_64 mt;
uniform_int_distribution<int> uid( INT_MAX, INT_MAX );
vector<int> vi;
vi.reserve( 1'000 );
for( size_t i = vi.capacity(); i--; )
vi.emplace_back( uid( mt ) );
unordered_map<void const *, size_t> addresses;
bool invert = argc > 1;
sort( vi.begin(), vi.end(),
[&, invert = invert]( int lhs, int rhs )
{
++addresses[&invert];
if( !invert )
return lhs < rhs;
else
return rhs < lhs;
} );
for( auto &pCount : addresses )
cout << pCount.first << ": " << pCount.second << endl;
}
I think for std::sort it would be the best to store the complete
state the lambda refers to as a static or thread_local variable
that the lambda itself doesn't need any state to be copied that
there's actually no parameter passed through the recursion.