STL常用


nth_element(first,nth,last)

first,last 第一个和最后一个迭代器,也可以直接用数组的位置。
将第n个大的元素放到nth位置上,左边元素都小于它,右边元素都大于它.

// nth_element example
#include <iostream>     // std::cout
#include <algorithm>    // std::nth_element, std::random_shuffle
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<10; i++) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

  std::random_shuffle (myvector.begin(), myvector.end());

  // using default comparison (operator <):
  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end());

  // using function as comp
  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end(),myfunction);

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '
';

  return 0;
}


//Possible output:
//myvector contains: 3 1 4 2 5 6 9 7 8


std::fill std::fill_n

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
 
int main()
{
    std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    std::fill_n(v.begin(), 5, -1);
 
    std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "
";
    //Output:
    //-1 -1 -1 -1 -1 5 6 7 8 9

    std::fill(v.begin(), v.end(), -1);
 
    for (auto elem : v) {
        std::cout << elem << " ";
    }
    std::cout << "
";
    //Output:
    //-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
}

std::priority_queue

priority_queue 容器适配器定义了一个元素有序排列的队列。默认队列头部的元素优先级最高。

priority_queue 模板有 3 个参数,其中两个有默认的参数;第一个参数是存储对象的类型,第二个参数是存储元素的底层容器,第三个参数是函数对象,它定义了一个用来决定元素顺序的断言。因此模板类型是:

template <typename T, typename Container=std::vector<T>, typename Compare=std::less<T>> class priority_queue

对 priority_queue 进行操作有一些限制:

  • push(const T& obj):将obj的副本放到容器的适当位置,这通常会包含一个排序操作。
  • push(T&& obj):将obj放到容器的适当位置,这通常会包含一个排序操作。
  • emplace(T constructor a rgs...):通过调用传入参数的构造函数,在序列的适当位置构造一个T对象。为了维持优先顺序,通常需要一个排序操作。
  • top():返回优先级队列中第一个元素的引用。
  • pop():移除第一个元素。
  • size():返回队列中元素的个数。
  • empty():如果队列为空的话,返回true。
  • swap(priority_queue& other):和参数的元素进行交换,所包含对象的类型必须相同。
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
 
using namespace std;
 
int main()
{
    priority_queue <int, vector<int>, greater<int>> pq1;
    priority_queue <int, vector<int>, less<int>> pq2;
 
    for (int i=0; i<8; ++i) {
        pq1.push(i);
        pq2.push(i);
    }
    cout << "pq1: ";
    while (!pq1.empty()) {
        cout << pq1.top() << " ";
        pq1.pop();
    }
    cout << endl;
 
    cout << "pq2: ";
    while (!pq2.empty()) {
        cout << pq2.top() << " ";
        pq2.pop();
    }
    cout <<endl;
    return 0;
}

\pq1: 0 1 2 3 4 5 6 7
\pq2: 7 6 5 4 3 2 1 0

原文地址:https://www.cnblogs.com/narjaja/p/10839747.html