Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Lambda passed through a std::sort recursion

24 views
Skip to first unread message

Bonita Montero

unread,
Nov 19, 2023, 6:04:25 AM11/19/23
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.
0 new messages