c++ - Why does vector not have sort() method as a member function of vector, while list does? -
there sort() method lists in stl. absurd, because more inclined sort array/vector. why isn't sort() provided vector? there underlying philosophy behind creation of vector container or usage, sort not provided it?
as has been said, standard library provides nonmember function template can sort range given pair of random access iterators.
it entirely redundant have member function sort vector. following have same meaning:
std::sort(v.begin(), v.end()); v.sort(); one of first principles of stl algorithms not coupled containers. how data stored , how data manipulated should loosely coupled possible.
iterators used interface between containers (which store data) , algorithms (which operate on data). in way, can write algorithm once , can operate on containers of various types, , if write new container, existing generic algorithms can used manipulate contents.
the reason std::list provides own sort function member function is not random accessible container; provides bidirectional iterators (since intended represent doubly linked list, makes sense). generic std::sort function requires random access iterators, cannot use std::list. std::list provides own sort function in order can sorted.
in general, there 2 cases in container should implement algorithm:
if generic algorithm cannot operate on container, there different, container-specific algorithm can provide same functionality, case
std::list::sort.if container can provide specific implementation of algorithm more efficient generic algorithm, case
std::map::find, allows element found in map in logarithmic time (the genericstd::findalgorithm performs linear search because cannot assume range sorted).
Comments
Post a Comment