Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8821359
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:50:03+00:00 2026-06-14T05:50:03+00:00

According to SGI, cplusplus.com, and every other source I’ve got, the sort() member function

  • 0

According to SGI, cplusplus.com, and every other source I’ve got, the sort() member function of the std::list should not invalidate iterators. However, that doesn’t seem to be the case when I run this code (c++11):

#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include "print.hpp"
unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_int_distribution<unsigned int> distribution(1, 1000000000);
auto rng = std::bind(distribution, generator);
// C++11 RNG stuff. Basically, rng() now gives some unsigned int [1, 1000000000]

int main() {
    unsigned int values(0);
    std::cin >> values;           // Determine the size of the list
    std::list<unsigned int> c;
    for (unsigned int n(0); n < values; ++n) {
        c.push_front(rng());
    }
    auto c0(c);
    auto it(c.begin()), it0(c0.begin());
    for (unsigned int n(0); n < 7; ++n) {
        ++it;     // Offset these iterators so I can print 7 values
        ++it0;
    }
    std::cout << "With seed: " << seed << "\n";
    std::cout << "Unsorted list: \n";
    print(c.begin(), c.end()) << "\n";
    print(c.begin(), it) << "\n\n";
    auto t0 = std::chrono::steady_clock::now();
    c0.sort();
    auto d0 = std::chrono::steady_clock::now() - t0;
    std::cout << "Sorted list: \n";
    print(c0.begin(), c0.end()) << "\n";
    print(c0.begin(), it0) << "\n";  // My own print function, given further below
    std::cout << "Seconds: " << std::chrono::duration<double>(d0).count() << std::endl;
    return 0;
}

In print.hpp:

#include <iostream>

template<class InputIterator>
std::ostream& print(InputIterator begin, const InputIterator& end, 
                    std::ostream& out = std::cout) {
    bool first(true);
    out << "{";
    for (; begin != end; ++begin) {
        if (first) {
            out << (*begin);
            first = false;
        } else {
            out << ", " << (*begin);
        }
    }
    out << "}";
    return out;
}

Sample input/output:

11
With seed: 3454921017
Unsorted list: 
{625860546, 672762972, 319409064, 8707580, 317964049, 762505303, 756270868, 249266563, 224065083, 843444019, 523600743}
{625860546, 672762972, 319409064, 8707580, 317964049, 762505303, 756270868}

Sorted list: 
{8707580, 224065083, 249266563, 317964049, 319409064, 523600743, 625860546, 672762972, 756270868, 762505303, 843444019}
{8707580, 224065083}
Seconds: 2.7e-05

Everything works as expected, except for the printing. It is supposed to show 7 elements, but instead the actual number is fairly haphazard, provided “value” is set to more than 7. Sometimes it gives none, sometimes it gives 1, sometimes 10, sometimes 7, etc.
So, is there something observably wrong with my code, or does this indicate that g++’s std::list (and std::forward_list) is not standards conforming?

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:50:04+00:00Added an answer on June 14, 2026 at 5:50 am

    The iterators remain valid and still refer to the same elements of the list, which have been re-ordered.

    So I don’t think your code does what you think it does. It prints the list from the beginning, to wherever the 7th element ended up after the list was sorted. The number of elements it prints therefore depends on the values in the list, of course.

    Consider the following code:

    #include <list>
    #include <iostream>
    
    int main() {
        std::list<int> l;
        l.push_back(1);
        l.push_back(0);
        std::cout << (void*)(&*l.begin()) << "\n";
        l.sort();
        std::cout << (void*)(&*l.begin()) << "\n";
    }
    

    The two address printed differ, showing that (unlike std::sort), std::list::sort has sorted by changing the links between the elements, not by assigning new values to the elements.

    I’ve always assumed that this is mandated (likewise for reverse()). I can’t actually find explicit text to say so, but if you look at the description of merge, and consider that the reason for list::sort to exist is presumably because mergesort works nicely with lists, then I think it’s “obviously” intended. merge says, “Pointers and references to the moved elements of x now refer to those same elements but as members of *this” (23.3.5.5./23), and the start of the section that includes merge and sort says, “Since lists allow fast insertion and erasing from the middle of a list, certain operations are provided specifically for them” (23.3.5.5/1).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

According to docs at http://code.google.com/p/minify/wiki/UriRewriting $min_serveOptions['rewriteCssUris'] = false; I should be able to add
The following is the definition of copy, according to http://www.sgi.com/tech/stl/copy.html . template<class InputIterator, class
According to http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html - Status bar icons should be white without any color. Many
According to http://msdn.microsoft.com/en-us/library/ms535934(v=VS.85).aspx and http://msdn.microsoft.com/en-us/library/ms535262(v=VS.85).aspx , I should be able to do the following
According to this MSDN article , you should not catch general exceptions. I'm sure
According to the annotated source, the Coffee Script grammar delimits the arguments to a
According to connects documentation the session should expire when the browser is closed: By
According to the docs: You should not override init. You are discouraged from overriding
According to JavaScript Patterns book (p. 79), this should work: var ob = {
according to https://developers.google.com/web-toolkit/doc/latest/DevGuideUiPanels#Standards I 'm not suppose to use DockPanel, VerticalPanel, HorizontalPanel. But Those

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.