Does the STL have a way to apply a function before calling less than? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceDoes the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?Pretty-print C++ STL containersElegant way to find closest value in a vector from aboveLess-than function dereferencing pointersShould custom containers have free begin/end functions?why do std::sort and partial_sort require random-access iterators?c++ Sort Vector based on distance to external PointHow can I avoid “for” loops with an “if” condition inside them with C++?Do STL algorithms functions, like accumulate, avoid copy if the function passed to them accepts a reference?Why does std::sort segfault with non-transitive comparators?

Is there folklore associating late breastfeeding with low intelligence and/or gullibility?

Can I throw a sword that doesn't have the Thrown property at someone?

New Order #5: where Fibonacci and Beatty meet at Wythoff

How to pour concrete for curved walkway to prevent cracking?

Direct Experience of Meditation

What was Bilhah and Zilpah's ancestry?

Replacing HDD with SSD; what about non-APFS/APFS?

Can a 1st-level character have an ability score above 18?

Estimate capacitor parameters

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

How to dynamically generate the hash value of a file while it gets downloaded from any website?

Communication vs. Technical skills ,which is more relevant for today's QA engineer positions?

Single author papers against my advisor's will?

Can't figure this one out.. What is the missing box?

Was credit for the black hole image misattributed?

Why does tar appear to skip file contents when output file is /dev/null?

How to rotate it perfectly?

How did the aliens keep their waters separated?

Autumning in love

I'm having difficulty getting my players to do stuff in a sandbox campaign

If I can make up priors, why can't I make up posteriors?

Limit for e and 1/e

How to retrograde a note sequence in Finale?

Active filter with series inductor and resistor - do these exist?



Does the STL have a way to apply a function before calling less than?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceDoes the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?Pretty-print C++ STL containersElegant way to find closest value in a vector from aboveLess-than function dereferencing pointersShould custom containers have free begin/end functions?why do std::sort and partial_sort require random-access iterators?c++ Sort Vector based on distance to external PointHow can I avoid “for” loops with an “if” condition inside them with C++?Do STL algorithms functions, like accumulate, avoid copy if the function passed to them accepts a reference?Why does std::sort segfault with non-transitive comparators?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








9















A lot of algorithms accept a comparison object. Often, I end up with something like



std::sort(begin, end, [&](auto const& lhs, auto const& rhs) 
return Function(lhs) < Function(rhs);
);


Is there anything in the STL to apply a Function before calling less than? So I could write:



std::sort(begin, end, std::DoesThisExist(Function));


I know I could write my own, but I wonder if this already exists. I glanced through cpprefence but didn't see it. Could easily have missed it.










share|improve this question







New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • I don't think this exists, however, it should be very easy to write.

    – JVApen
    3 hours ago

















9















A lot of algorithms accept a comparison object. Often, I end up with something like



std::sort(begin, end, [&](auto const& lhs, auto const& rhs) 
return Function(lhs) < Function(rhs);
);


Is there anything in the STL to apply a Function before calling less than? So I could write:



std::sort(begin, end, std::DoesThisExist(Function));


I know I could write my own, but I wonder if this already exists. I glanced through cpprefence but didn't see it. Could easily have missed it.










share|improve this question







New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • I don't think this exists, however, it should be very easy to write.

    – JVApen
    3 hours ago













9












9








9








A lot of algorithms accept a comparison object. Often, I end up with something like



std::sort(begin, end, [&](auto const& lhs, auto const& rhs) 
return Function(lhs) < Function(rhs);
);


Is there anything in the STL to apply a Function before calling less than? So I could write:



std::sort(begin, end, std::DoesThisExist(Function));


I know I could write my own, but I wonder if this already exists. I glanced through cpprefence but didn't see it. Could easily have missed it.










share|improve this question







New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












A lot of algorithms accept a comparison object. Often, I end up with something like



std::sort(begin, end, [&](auto const& lhs, auto const& rhs) 
return Function(lhs) < Function(rhs);
);


Is there anything in the STL to apply a Function before calling less than? So I could write:



std::sort(begin, end, std::DoesThisExist(Function));


I know I could write my own, but I wonder if this already exists. I glanced through cpprefence but didn't see it. Could easily have missed it.







c++






share|improve this question







New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 5 hours ago









Fomar putesFomar putes

483




483




New contributor




Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Fomar putes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • I don't think this exists, however, it should be very easy to write.

    – JVApen
    3 hours ago

















  • I don't think this exists, however, it should be very easy to write.

    – JVApen
    3 hours ago
















I don't think this exists, however, it should be very easy to write.

– JVApen
3 hours ago





I don't think this exists, however, it should be very easy to write.

– JVApen
3 hours ago












2 Answers
2






active

oldest

votes


















4














The STL should have a sort that works on a transform of the elements rather than the elements themselves. The reason for this being that Function could actually be costly. By simply incorporating it into the comparison as you did you invoke Function nlog(n) times rather than the optimal n.




To sort arrays in parallel using STL algorithm :




std::sort(std::execution::par, container.begin(), container.end(), comparison_object);


Anyway, I think if you try to just sort with ranges::view::transform it will probably still call your function ~n log n many times. But you could just do something like:



auto values = /* some container */;
auto keys = values | ranges::view::transform(f) | ranges::to_vector;
ranges::sort(ranges::view::zip(keys, values),
[](auto const& x, auto const& y) return std::get<0>(x) < std::get<0>(y); );





share|improve this answer























  • Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

    – Davis Herring
    56 mins ago


















1














The Ranges TS (which has been merged for C++20) defines variations of many of the standard algorithms that include projections with exactly this behavior.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Fomar putes is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55678360%2fdoes-the-stl-have-a-way-to-apply-a-function-before-calling-less-than%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    The STL should have a sort that works on a transform of the elements rather than the elements themselves. The reason for this being that Function could actually be costly. By simply incorporating it into the comparison as you did you invoke Function nlog(n) times rather than the optimal n.




    To sort arrays in parallel using STL algorithm :




    std::sort(std::execution::par, container.begin(), container.end(), comparison_object);


    Anyway, I think if you try to just sort with ranges::view::transform it will probably still call your function ~n log n many times. But you could just do something like:



    auto values = /* some container */;
    auto keys = values | ranges::view::transform(f) | ranges::to_vector;
    ranges::sort(ranges::view::zip(keys, values),
    [](auto const& x, auto const& y) return std::get<0>(x) < std::get<0>(y); );





    share|improve this answer























    • Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

      – Davis Herring
      56 mins ago















    4














    The STL should have a sort that works on a transform of the elements rather than the elements themselves. The reason for this being that Function could actually be costly. By simply incorporating it into the comparison as you did you invoke Function nlog(n) times rather than the optimal n.




    To sort arrays in parallel using STL algorithm :




    std::sort(std::execution::par, container.begin(), container.end(), comparison_object);


    Anyway, I think if you try to just sort with ranges::view::transform it will probably still call your function ~n log n many times. But you could just do something like:



    auto values = /* some container */;
    auto keys = values | ranges::view::transform(f) | ranges::to_vector;
    ranges::sort(ranges::view::zip(keys, values),
    [](auto const& x, auto const& y) return std::get<0>(x) < std::get<0>(y); );





    share|improve this answer























    • Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

      – Davis Herring
      56 mins ago













    4












    4








    4







    The STL should have a sort that works on a transform of the elements rather than the elements themselves. The reason for this being that Function could actually be costly. By simply incorporating it into the comparison as you did you invoke Function nlog(n) times rather than the optimal n.




    To sort arrays in parallel using STL algorithm :




    std::sort(std::execution::par, container.begin(), container.end(), comparison_object);


    Anyway, I think if you try to just sort with ranges::view::transform it will probably still call your function ~n log n many times. But you could just do something like:



    auto values = /* some container */;
    auto keys = values | ranges::view::transform(f) | ranges::to_vector;
    ranges::sort(ranges::view::zip(keys, values),
    [](auto const& x, auto const& y) return std::get<0>(x) < std::get<0>(y); );





    share|improve this answer













    The STL should have a sort that works on a transform of the elements rather than the elements themselves. The reason for this being that Function could actually be costly. By simply incorporating it into the comparison as you did you invoke Function nlog(n) times rather than the optimal n.




    To sort arrays in parallel using STL algorithm :




    std::sort(std::execution::par, container.begin(), container.end(), comparison_object);


    Anyway, I think if you try to just sort with ranges::view::transform it will probably still call your function ~n log n many times. But you could just do something like:



    auto values = /* some container */;
    auto keys = values | ranges::view::transform(f) | ranges::to_vector;
    ranges::sort(ranges::view::zip(keys, values),
    [](auto const& x, auto const& y) return std::get<0>(x) < std::get<0>(y); );






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 3 hours ago









    Ben Chaliah AyoubBen Chaliah Ayoub

    2,422217




    2,422217












    • Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

      – Davis Herring
      56 mins ago

















    • Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

      – Davis Herring
      56 mins ago
















    Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

    – Davis Herring
    56 mins ago





    Calling a transform n log n times matters only if its expense is significant compared to the comparison and permutation. In common cases where the “transform” is just selecting a member or performing simple arithmetic, allocating the space for the key values would be much worse than the repeated work.

    – Davis Herring
    56 mins ago













    1














    The Ranges TS (which has been merged for C++20) defines variations of many of the standard algorithms that include projections with exactly this behavior.






    share|improve this answer



























      1














      The Ranges TS (which has been merged for C++20) defines variations of many of the standard algorithms that include projections with exactly this behavior.






      share|improve this answer

























        1












        1








        1







        The Ranges TS (which has been merged for C++20) defines variations of many of the standard algorithms that include projections with exactly this behavior.






        share|improve this answer













        The Ranges TS (which has been merged for C++20) defines variations of many of the standard algorithms that include projections with exactly this behavior.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 4 hours ago









        Davis HerringDavis Herring

        9,1001736




        9,1001736




















            Fomar putes is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Fomar putes is a new contributor. Be nice, and check out our Code of Conduct.












            Fomar putes is a new contributor. Be nice, and check out our Code of Conduct.











            Fomar putes is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55678360%2fdoes-the-stl-have-a-way-to-apply-a-function-before-calling-less-than%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Isurus Índice Especies | Notas | Véxase tamén | Menú de navegación"A compendium of fossil marine animal genera (Chondrichthyes entry)"o orixinal"A review of the Tertiary fossil Cetacea (Mammalia) localities in wales port taf Museum Victoria"o orixinalThe Vertebrate Fauna of the Selma Formation of Alabama. Part VII. Part VIII. The Mosasaurs The Fishes50419737IDsh85068767Isurus2548834613242066569678159923NHMSYS00210535017845105743

            Is 1 ppb equal to 1 μg/kg? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)How to determine the concentration after a dilution with Beer's law?What would be SMILES notation for a compound with delocalized bonding?Amount of substance of a molecule in a solute the same as amount of substance of constituent elements?Interpreting notation format 1.64E-02 from particulate emission dataWhat was the lithium concentration in 1940's 7-Up?Why are osmoles not considered SI units?Why is Ka constant when volume is increased?Should residual sodium be considered in measuring sodium content of sweat?Concentration of mercury in bodyConversion from a PPB value to µg/m3 of Isobutylene

            What does “fit” mean in this sentence? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)How does 'jealousy' mean 'suspicion'?What does “not so say” mean?Does “somebody of my caliber” mean the speaker themselves?“accounting for high fasting blood glucose”- help about the meaningWhat does “cloaked by NDA” mean in this context?What does it mean by 'community ownership' in this context?What does “human corroborators” mean in this context?What does “everything but a fire” mean in this context?What does “run” mean here?What does “rabbited” mean/imply in this sentence?