C++ `std::set` 是否在每种情况下都对元素进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11809163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:33:57  来源:igfitidea点击:

Does `std::set` sort elements in every case?

c++sortingstlsetstd

提问by kravemir

From cplusplus.comreference it seems that std::setsorts elements.

cplusplus.com参考来看,似乎对std::set元素进行了排序。

I need to have sorted strings, but I'm not sure if it will work well on every platform and compiler. Mainly GCC, MinGW, VC.

我需要对字符串进行排序,但我不确定它是否适用于每个平台和编译器。主要是GCC、MinGW、VC。

回答by Daniel A. White

By its definition std::setis a sorted container. Its part of the standard. Having it sorted helps maintain that its a set rather than just an arbitrary collection.

根据它的定义,它std::set是一个排序的容器。它是标准的一部分。对它进行排序有助于保持它是一个集合而不仅仅是一个任意集合。

Source: http://www.sgi.com/tech/stl/set.html

来源:http: //www.sgi.com/tech/stl/set.html

回答by Sergey Vystoropskyi

Actualy std::set and std::map are not really sorted. Both of these containers are implemented as a red-black trees. So when you iterate such kind of containers, iterator walks through the tree in such way that it looks like that container is sorted. At first it visits the most left node then the parent of the most left one and so on...

实际上 std::set 和 std::map 并没有真正排序。这两个容器都实现为红黑树。因此,当您迭代此类容器时,迭代器会以看起来该容器已排序的方式遍历树。首先它访问最左边的节点,然后访问最左边的节点的父节点,依此类推......

回答by TemplateRex

Yes, std::setstores its elements in such a way that iterating over the elements will be done in sorted order (and the call to std::adjacent_findis to show that std::setstores unique items as well).

是的,std::set以这样一种方式存储它的元素,即迭代元素将按排序顺序完成(并且调用std::adjacent_find是为了显示std::set存储唯一项)。

#include <algorithm>
#include <iterator>
#include <ios>
#include <iostream>
#include <set>
#include <string>

int main()
{
    auto const ss = std::set<std::string> { "foo", "bar", "test" };
    std::cout << std::boolalpha << std::is_sorted(begin(ss), end(ss)) << "\n";
    std::cout << std::boolalpha << (std::adjacent_find(begin(ss), end(ss)) == end(ss)) << "\n";
    std::copy(begin(ss), end(ss), std::ostream_iterator<std::string>(std::cout, "\n"));
}

Live Example

现场示例