c++ - std::sort doing lots of unnecessary swaps -
i have following code try lexicographical comparison of 2 simple vectors
class expensiveclass { public: static int increment; std::vector<int> bigvector; expensiveclass() { (int j = 0; j < 1 + increment; ++j) bigvector.emplace_back(j); ++increment; } expensiveclass(const expensiveclass& other) { std::cout << "expensive copy constructor called!" << std::endl; this->bigvector = other.bigvector; } }; int expensiveclass::increment = 0; bool sortfunc(const expensiveclass& a, const expensiveclass& b) { bool ret = a.bigvector < b.bigvector; if (ret == false) std::cout << "need swap" << std::endl; return ret; } int main() { std::vector<expensiveclass> vectorofvectors; vectorofvectors.reserve(100); (int = 0; < 100; ++i) vectorofvectors.emplace_back(); std::cout << "start sorting.." << std::endl; std::sort(vectorofvectors.begin(), vectorofvectors.end(), sortfunc); } and i'd know why std::sort doing lots of swaps on sorted vector?
i think we're getting dark corners of stl here. played code , discovered sortfunc() doesn't return true. because arguments being passed not in order. std::sort algorithm picks elements vectorofvectors out of order, i.e. index of a within vectorofvectors not guaranteed higher index of b. don't know how dig deeper created separate questions: https://stackoverflow.com/questions/30539898/counter-intuitive-behavior-of-stdsort
anyway, point made assumption on behavior of std::sort, that's implementation dependent.
Comments
Post a Comment