对 std::vector> 进行排序通过字符串?
如何通过比较 pair.first
(即 std::string
)来对这个向量
进行排序? (不提供静态比较函数,也不使用boost)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用自定义比较器仅对配对的
.first
进行排序。You can use a custom comparator to order on the pairs'
.first
only.您不需要提供任何比较函数,因为默认情况下, sort() 函数将以值的升序对向量进行排序。由于每个元素都是一对,因此如果一对的第一个值小于另一对的第一个值,则一对将小于另一对。
You don't need to provide any compare function since by default since the sort() function will sort vector in ascending order of values. As each element is a pair, so one pair will be smaller than other one if the first value of one pair is smaller than that for other pair.
std::pair
重载operator<
以首先按first
元素排序,然后按second
元素排序。因此,如果您仅使用默认排序顺序(operator<
)对向量
进行排序,您将获得所需的排序。std::pair
overloadsoperator<
to sort first by thefirst
element then by thesecond
element. Thus, if you just sort thevector
using the default sort ordering (operator<
), you'll get your desired ordering.我真的很喜欢詹姆斯的回答,但是您可能还需要考虑另一种选择 - 将所有内容都集中到 std::map 中:
或者,如果您有重复的字符串,则将所有内容都集中到 std:: multimap:
这确实有一个额外的优点,如果您需要添加或删除新的键/值对,您可以在 O(lg n) 中完成此操作,而不是排序向量的 O(n) 中。
如果您确实必须使用向量,请遵循詹姆斯的答案。但是,如果您有一个成对的向量,那么您很可能确实需要一个
std::map
。I really like James' answer, but there's one other option you might want to consider - just funnel everything into a
std::map
:Or, if you have duplicate strings, a
std::multimap
:This does have the added advantage that if you then need to add or remove new key/value pairs, you can do so in O(lg n), as opposed to O(n) for the sorted vector.
If you really must use a vector, then go with James' answer. However, if you have a vector of pairs, there's a good chance that you really want a
std::map
.回答“重复问题”:
链接: 在 C++ 中按第一个元素然后按对的第二个元素对向量对进行排序?
Answer to "duplicate question" of this:
link: Sort a vector of pairs by first element then by second element of the pair in C++?