21xrx.com
2025-03-29 20:27:50 Saturday
文章检索 我的文章 写文章
C++ 容器的排序方法
2023-06-29 04:19:05 深夜i     13     0
C++ 容器 排序方法

C++是一种非常强大的编程语言,它具有许多功能,在其标准库中,我们可以使用各种容器,如数组、向量、列表、队列和映射等。但是,当我们需要对这些容器中的元素进行排序时,C++提供了不同的方法,本文将介绍这些方法。

1. sort()函数

C++的标准库提供了一个名为sort()函数的函数,它可以对大多数容器进行排序。sort()函数最常用的形式接受两个迭代器,并将它们之间的范围排序。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 5;
  sort(nums.begin(), nums.end());
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:1 1 3 4 5 9

2. stable_sort()函数

stable_sort()函数与sort()函数类似,但它保证相等元素的相对顺序不变。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Person
  int age;
  string name;
;
bool cmp(const Person &a, const Person &b)
  return a.age < b.age;
int main()
{
  vector<Person> persons{
    25,
     "Ken",
    25,
    18
  };
  stable_sort(persons.begin(), persons.end(), cmp);
  for(auto person : persons)
    cout << person.age << " " << person.name << endl;
  
  return 0;
}
/*
输出结果:
18 John
19 Ken
25 Tom
25 Alice
*/

3. partial_sort()函数

partial_sort()函数用于部分排序,即只需要将前几个元素进行排序。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 1;
  partial_sort(nums.begin(), nums.begin() + 3, nums.end());
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:1 1 3 4 5 9

4. nth_element()函数

nth_element()函数用于找出序列中的第N个元素,并将它放在正确的位置上。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 9;
  nth_element(nums.begin(), nums.begin() + 2, nums.end());
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:1 1 3 5 4 9

5. make_heap()函数

make_heap()函数将序列转换为堆,即每个节点都比其子节点大。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 4;
  make_heap(nums.begin(), nums.end());
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:9 5 4 1 1 3

6. push_heap()函数

push_heap()函数将新元素添加到堆中,并将其放在正确的位置上。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 1;
  make_heap(nums.begin(), nums.end());
  nums.push_back(6);
  push_heap(nums.begin(), nums.end());
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:9 6 4 1 1 3 5

7. pop_heap()函数

pop_heap()函数将堆的最大元素从序列中移除,并将其放在最后一个元素的位置上。以下是一个例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> nums 5;
  make_heap(nums.begin(), nums.end());
  pop_heap(nums.begin(), nums.end());
  nums.pop_back();
  for(int num : nums)
    cout << num << " ";
  
  return 0;
}
// 输出结果:4 1 3 1 5

总结

以上介绍的是C++的容器排序方法,sort()函数是最常用的排序函数,而其他函数则可以更好地满足特定需求。学习并掌握这些函数可以更好地利用C++容器所提供的功能。

  
  

评论区

请求出错了