为什么vector不具有sort()方法作为vector的成员函数,而list却具有呢? [英] Why does vector not have sort() method as a member function of vector, while list does?

查看:341
本文介绍了为什么vector不具有sort()方法作为vector的成员函数,而list却具有呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在STL中有一个sort()方法用于列表.这很荒谬,因为我更倾向于对数组/向量进行排序. 为什么没有为vector提供sort()?在创建矢量容器或其用法之后,是否存在一些基本原理,而没有为其提供这种排序?

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 underlying philosophy behind the creation of the vector container or its usage, that sort is not provided for it?

推荐答案

如前所述,标准库提供了一个非成员函数模板,该模板可以在给定一对随机访问迭代器的情况下对任何范围进行排序.

As has already been said, the standard library provides a nonmember function template that can sort any range given a pair of random access iterators.

使用成员函数对向量进行排序将完全多余.以下内容将具有相同的含义:

It would be entirely redundant to have a member function to sort a vector. The following would have the same meaning:

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

STL的首要原则之一是算法不与容器耦合.数据的存储方式和数据的处理方式应尽可能松散地耦合.

One of the first principles of the STL is that algorithms are not coupled to containers. How data is stored and how data is manipulated should be as loosely coupled as possible.

迭代器用作容器(用于存储数据)和算法(用于数据)之间的接口.这样,您只需编写一次算法就可以对各种类型的容器进行操作,并且如果您编写新的容器,则可以使用现有的通用算法来操纵其内容.

Iterators are used as the interface between containers (which store data) and algorithms (which operate on the data). In this way, you can write an algorithm once and it can operate on containers of various types, and if you write a new container, the existing generic algorithms can be used to manipulate its contents.

std::list提供其自己的sort函数作为成员函数的原因是,它不是随机可访问的容器;它仅提供双向迭代器(因为它旨在表示双向链表,因此很有意义).通用std::sort函数需要随机访问迭代器,因此您不能将其与std::list一起使用. std::list提供了自己的sort函数,以便可以对其进行排序.

The reason that std::list provides its own sort function as a member function is that it is not a random accessible container; it only provides bidirectional iterators (since it is intended to represent a doubly linked list, this makes sense). The generic std::sort function requires random access iterators, so you cannot use it with a std::list. std::list provides its own sort function in order that it can be sorted.

通常,在两种情况下,容器应实现一种算法:

In general, there are two cases in which a container should implement an algorithm:

  • 如果通用算法无法在容器上运行,但是存在与容器特定的不同算法,可以提供与std::list::sort相同的功能.

如果容器可以提供比通用算法更有效的算法的特定实现,例如std::map::find的情况,它允许在对数时间内在地图中找到一个元素(通用std::find算法执行线性搜索,因为它不能假定范围已排序.)

If the container can provide a specific implementation of the algorithm that is more efficient than the generic algorithm, as is the case with std::map::find, which allows an element to be found in the map in logarithmic time (the generic std::find algorithm performs a linear search because it cannot assume the range is sorted).

这篇关于为什么vector不具有sort()方法作为vector的成员函数,而list却具有呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆