Why does vector not have sort() method as a member function of vector, while list does?

前端 未结 6 1474
感动是毒
感动是毒 2021-01-11 09:29

There is a sort() method for lists in STL. Which is absurd, because I would be more inclined to sort an array/vector. Why isn\'t sort() provided for vector? Is there some un

6条回答
  •  迷失自我
    2021-01-11 10:21

    You can easily sort a vector with:

    sort(v.begin(), v.end());
    

    UPDATE: (answer to the comment): Well, they have certainly provided it by default. The difference is that it's not a member function for vector. std::sort is a generic algorithm that's supposed to work for anything that provides iterators. However, it really expects a random access iterator to sort efficiently. std::list, being a linked list, cannot provide random access to its elements efficiently. That's why it provides its own specialized sort algorithm.

提交回复
热议问题