C++ 2D vector的默认排序行为是什么?

huangapple go评论57阅读模式
英文:

What is the default sort behavior of a C++ 2D vector?

问题

当使用stl:sort()对2D向量进行排序时,其默认排序行为是什么?我想知道如果存在并列情况会发生什么?默认比较器会如何工作?

英文:

When sorting a 2d vector using stl:sort(), what is its default sort behavior? I would like to know what happens if there are ties? How would the default comparator work?

答案1

得分: 3

它在两个 std::vector 层面上进行词典顺序比较。这是因为 std::vector::operator< 被指定为按词典顺序比较元素,并且默认情况下 std::sort 使用 < 来比较元素。

std::sort 将始终不指定等价元素的顺序。然而,std::stable_sort 将保持等价元素的顺序与它们的原始顺序相同(并且因此能够这样做而产生性能损失)。

英文:

It compares lexicographically with respect to both std::vector layers. That's because std::vector::operator< is specified to compare elements lexicographically and by default std::sort uses < to compare elements.

std::sort will always leave the order of equivalent elements unspecified. std::stable_sort will however leave the order of equivalent elements identical to their original order (and incurs a performance penalty for being able to do so).

答案2

得分: 0

以下是您提供的代码的中文翻译:

除了其他人的答案之外,这里有一个简单的示例(可能需要较新版本的C++):

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    auto x = vector<int>{4, 2, 7};
    sort(x.begin(), x.end());
    for (auto e : x)
        cout << e << " ";
    cout << endl;

    auto y = vector<vector<int>>{
        vector<int>{1, 123},
        vector<int>{2, 3},
        vector<int>{3, 2},
        vector<int>{1, 7},
        vector<int>{2, 3}
    };
    sort(y.begin(), y.end());
    for (auto e : y)
        cout << e[0] << "," << e[1] << " ";
    cout << endl;
}

请注意,我只提供了代码的翻译,没有其他额外的内容。

英文:

In addition to the others' answers, here's a simple example (may require a recent version of C++):

#include &lt;algorithm&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int main ()
{
	auto x = vector{4,2,7};
	sort(x.begin(), x.end());
	for (auto e : x)
		cout &lt;&lt; e &lt;&lt; &quot; &quot;;
	cout &lt;&lt; endl;

	auto y = vector{
		vector{1,123},
		vector{2,3},
		vector{3,2},
		vector{1,7},
		vector{2,3}
	};
	sort(y.begin(), y.end());
	for (auto e : y)
		cout &lt;&lt; e[0] &lt;&lt; &quot;,&quot; &lt;&lt; e[1] &lt;&lt; &quot; &quot;;
	cout &lt;&lt; endl;
}

huangapple
  • 本文由 发表于 2023年5月15日 03:39:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定