std::list::reverse(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::list::reverse β€” std::list::reverse

okay so bestie, we're in the C++ Standard Libary corner of the manual today (yes that's the page's own spelling, don't come for me 🫢) and the main character of this page is a member function so tiny and so powerful that it literally just flips your whole list around. no cap. let's get into it ✨


🌸 SYNOPSIS 🌸

void reverse();  (noexcept since C++11)

it reverses the order of the elements in the container πŸŽ€ and here's the part everyone always asks about in the group chat: no references or iterators become invalidated. like, they all keep valid. they keep vibing. nothing gets left on read. πŸ’–


πŸ¦‹ PARAMETERS πŸ¦‹

(none) β€” she takes nothing, she just delivers 😌


πŸŽ€ RETURN VALUE πŸŽ€

(none) β€” returns nothing, but returns the vibe ✨


🧚 COMPLEXITY 🧚

Linear in the size of the container. so like, it's proportional to how much stuff you've got in there. no sneaky quadratic nonsense, we love to see it πŸ‘‘


πŸ”₯ EXAMPLE πŸ”₯

run this code, it's giving tutorial-classic:

// Run this code

#include <iostream>
#include <list>

std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (auto& i : list)
        ostr << ' ' << i;
    return ostr;
}

int main()
{
    std::list<int> list = {8, 7, 5, 9, 0, 1, 3, 2, 6, 4};
    std::cout << "initially: " << list << '\n';

    list.sort();
    std::cout << "ascending: " << list << '\n';

    list.reverse();
    std::cout << "descending:" << list << '\n';
}

✨ Output ✨

initially:  8 7 5 9 0 1 3 2 6 4
ascending:  0 1 2 3 4 5 6 7 8 9
descending: 9 8 7 6 5 4 3 2 1 0

watch her go from chaos β†’ sorted β†’ flipped. the character development?? immaculate. 🌈


πŸ’€ DEFECT REPORTS πŸ’€

so sometimes the standards committee has to go back and fix their own lore, and these are the behavior-changing defect reports that got applied retroactively to previously published C++ standards. history, but make it documentation πŸ“œ

  • LWG 1207 β€” applied to C++98. as published, it was unclear whether iterators and/or references will be invalidated. the correct behavior: they keep valid. not me being vague for an entire standard πŸ’€πŸ™ˆ

πŸ‘‘ SEE ALSO πŸ‘‘

  • sort β€” sorts the elements (public member function). different tool, different job, both iconic in their own lane 🫢

that's the whole page bestie, go forth and flip your lists πŸ’œ

✨ this page came from http://cppreference.com, dated 2024.06.10, and it's literally titled std::list::reverse(3) β€” mwah, mwah, mwah, sending you all the kisses, periodt πŸ’…πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from