Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, it's completely normal for the comparison function to be called more times than you have elements in the collection. That's part of what's meant when we say a sorting algorithm's <em>complexity</em> is O(<em>n</em> log <em>n</em>), for example. The number of comparisons performed on a collection of size <em>n</em> will be about <em>n</em> × log(<em>n</em>). (In fact, <em>n</em> is pretty much the <em>minimum</em> number of times to call it; otherwise, we wouldn't even be able to tell whether the collection was already sorted in the first place.)</p> <p>Second, you get an error when you make the parameters be const references because you've declared <code>GetDisplayOrder</code> as a non-const method. You're not allowed to call non-const member functions on a const object because the compiler assumes the method will attempt to modify the object, even though in this case it doesn't modify anything. Add <code>const</code> to the end of the declaration and definition:</p> <pre><code>int GetDisplayOrder() const; int Item::GetDisplayOrder() const { return display_order; } </code></pre> <p>Finally, there's the matter of the segmentation faults. The code you've shown here isn't enough to pinpoint a cause. You're correct that changing the way you pass the iterators to <code>sort</code> shouldn't have any effect. My suspicion is that your <code>Item</code> class needs a copy constructor and an assignment operator, but that they either aren't implemented, or they're not implemented properly. Sorting a vector obviously involves moving items around in the collection, and that requires a working assignment operator. Passing those items to your original comparison function, which accepted parameters by value instead of by const reference, requires a working copy constructor. If you're doing any dynamic memory allocation (such as with <code>new</code> or <code>malloc</code>) you need to make sure you either make a "deep copy" of the memory when you assign or copy an object, or you figure out a way for multiple objects to <em>share</em> the same allocation. If multiple objects think they all own the same block of memory, one of them is likely to free that memory before the others are finished with it, and that can certainly lead to segmentation faults (as you access freed memory).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload