📜  C++中STL组件的重要功能

📅  最后修改于: 2021-09-07 02:09:38             🧑  作者: Mango

C++
// C++ code
#include 
#include 
using namespace std;
 
int main()
{
    // Declaring the PAIR1 of int and char
    // IF pair is not initialized then ,
    // default value of int/double is 0 and
    // for string/char it is NULL
    pair PAIR1;
    cout << PAIR1.first << " ";
   
    // NULL value therefore, not displayed
    cout << PAIR1.second
         << endl;
 
    // Initializing the pair during it's Declaration
    pair PAIR2("GeeksForGeeks", 1.23);
    cout << PAIR2.first << " ";
    cout << PAIR2.second << endl;
 
    pair PAIR3;
     
    // Inserting Value in pair using make_pair function
    PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);
    cout << PAIR3.first << " ";
    cout << PAIR3.second << endl;
 
    pair PAIR4;
     
    // Inserting Value in pair using {}(curly brackets)
    PAIR4 = { 4, 8 };
    cout << PAIR4.first << " ";
    cout << PAIR4.second << endl;
 
    return 0;
}


C++
// C++ program to illustrate the
// function of vector in C++
#include 
 
// Header file for vector if
//  not included
#include 
using namespace std;
 
// Function to print the vector
void print(vector vec)
{
 
    // vec.size() gives the size
    // of the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
 
    cout << endl;
}
 
// Driver Code
int main()
{
    // Defining a vector
    vector vec;
 
    // Put all natural numbers
    // from 1 to 10 in vector
    for (int i = 1; i <= 10; i++) {
        vec.push_back(i);
    }
 
    cout << "Initial vector: ";
 
    // print the vector
    print(vec);
 
    // Size of vector
    cout << "Vector size: " << vec.size() << "\n";
 
    // Check of vector is empty
    if (vec.empty() == false)
        cout << "Is vector is"
             << " empty: False\n";
 
    // Popping out 10 form the vector
    vec.pop_back();
    cout << "Vector after popping: ";
    print(vec);
 
    // Deleting the first element
    // from the vector using erase()
    vec.erase(vec.begin());
    cout << "Vector after erase"
         << " first element: ";
    print(vec);
 
    // Clear the vector
    vec.clear();
    cout << "Vector after "
         << "clearing: None ";
    print(vec);
 
    // Check if vector is empty
    if (vec.empty() == true)
        cout << "Is vector is"
             << " empty: True\n";
}


C++
// C++ program to illustrate the
// function of stack in C++
#include 
 
// Header file for stack
#include 
using namespace std;
 
// Function to print the stack
void print(stack s)
{
 
    // Loops runs till stack
    // becomes empty
    while (s.empty() == false) {
 
        // Prints the top element
        cout << s.top() << " ";
 
        // Now pops the same top element
        s.pop();
    }
 
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Given char array
    char array[]
        = { 'G', 'E', 'E', 'K',
            'S', 'F', 'O', 'R', 'G',
            'E', 'E', 'K', 'S' };
 
    // Defining stack
    stack s;
 
    // Check if stack is empty
    if (s.empty() == true) {
        cout << "Stack is currently Empty"
            << "\n";
    }
    else {
        cout << "Stack is not empty"
            << "\n";
    }
 
    // Push elements in stack
    for (int i = sizeof(array) / sizeof(array[0]) - 1;
        i >= 0; i--) {
        s.push(array[i]);
    }
 
    // Size of stack
    cout << "Size of stack: "
        << s.size() << "\n";
 
    // Content of stack
    cout << "Stack initially: ";
    print(s);
 
    // Returning the top
    // element of the stack
    cout << "Top element: "
        << s.top() << "\n";
 
    // Popping the top
    // element in stack
    s.pop();
 
    cout << "Stack after 1"
        << "pop operation: ";
    print(s);
 
    // Now checking the top element
    cout << "Top element after popping: "
        << s.top() << "\n";
 
    // Size of stack
    cout << "Size of stack"
        << "after popping: "
        << s.size() << "\n";
 
    // Again checking if the
    // stack is empty
    if (s.empty() == true) {
        cout << "Stack is currently Empty"
            << "\n";
    }
    else {
        cout << "Stack is not empty"
            << "\n";
    }
    return 0;
}


C++
// C++ program to illustrate the
// function of vector in C++
#include 
 
// Header file for queue
#include 
using namespace std;
 
// Function to print the queue
void print(queue q)
{
    for (int i = 0; i < q.size(); i++) {
 
        // Printing the front element
        cout << q.front() << " ";
 
        // Popping the front element
        q.pop();
    }
 
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Given array
    char array[]
        = { 'G', 'E', 'E', 'K', 'S' };
 
    // Defining queue
    queue q;
 
    if (q.empty() == true) {
        cout << "Queue is empty\n";
    }
 
    for (int i = 0; i < 5; i++) {
        q.push(array[i]);
    }
 
    cout << "Queue Initially: ";
    print(q);
 
    // Front element
    cout << "Front element: "
        << q.front() << "\n";
 
    // Back element
    cout << "Back Element: "
        << q.back() << "\n";
 
    // Size of queue
    cout << "Size of queue: "
        << q.size() << "\n";
 
    // Empty
    if (q.empty() == false) {
        cout << "Queue is not empty\n";
    }
    return 0;
}


C++
// C++ program to illustrate the
// function of priority queue in C++
#include 
 
// Header file for priority
// queue, both MIN and MAX
#include 
using namespace std;
 
// Function to print the
// min priority queue
void print_min(
    priority_queue, greater > q)
{
    while (q.empty() == false)
    {
        // Print the front
        // element(MINIMUM)
        cout << q.top() << " ";
 
        // Pop the minimum
        q.pop();
    }
    cout << "\n";
}
 
// Function to print the
// min priority queue
void print_max(priority_queue q)
{
    while (q.empty() == false)
    {
        // Print the front
        // element(MAXIMUM)
        cout << q.top() << " ";
 
        // Pop the maximum
        q.pop();
    }
    cout << "\n";
}
 
// Driver Code
int main()
{
    // MIN priority queue
    priority_queue max_pq;
 
    // MAX priority_queue
    priority_queue, greater > min_pq;
 
    // Is queue empty
    if (min_pq.empty() == true)
        cout << "MIN priority "
             << "queue is empty\n";
 
    if (max_pq.empty() == true)
        cout << "MAX priority"
             << " queue is empty\n";
 
    cout << "\n";
 
    for (int i = 1; i <= 10; i++)
    {
        min_pq.push(i);
        max_pq.push(i);
    }
 
    cout << "MIN priority queue: ";
    print_min(min_pq);
 
    cout << "MAX priority queue: ";
    print_max(max_pq);
    cout << "\n";
 
    // Size
    cout << "Size of min pq: " << min_pq.size() << "\n";
    cout << "Size of max pq: " << max_pq.size() << "\n";
    cout << "\n";
 
    // Top element
    cout << "Top of min pq: " << min_pq.top() << "\n";
    cout << "Top of max pq: " << max_pq.top() << "\n";
    cout << "\n";
 
    // Pop the front element
    min_pq.pop();
    max_pq.pop();
 
    // Queus after popping
    cout << "MIN priority "
         << "queue after pop: ";
    print_min(min_pq);
    cout << "MAX priority "
         << "queue after pop: ";
    print_max(max_pq);
    cout << "\n";
 
    // Size after popping
    cout << "Size of min pq: " << min_pq.size() << "\n";
    cout << "Size of max pq: " << max_pq.size() << "\n";
    cout << "\n";
 
    // Is queue empty
    if (min_pq.empty() == false)
        cout << "MIN priority "
             << " queue is not empty\n";
 
    if (max_pq.empty() == false)
        cout << "MAX priority queue"
             << " is not empty\n";
}


C++
// C++ code
#include 
#include 
using namespace std;
 
int main()
{
    // Declaring the PAIR1 of int and char
    // IF pair is not initialized then ,
    // default value of int/double is 0
    // and for string/char it is NULL
    pair PAIR1;
    cout << PAIR1.first << " ";
   
    // NULL value therefore, not displayed
    cout << PAIR1.second
         << endl;
 
    // Initializing the pair during it's Declaration
    pair PAIR2("GeeksForGeeks", 1.23);
    cout << PAIR2.first << " ";
    cout << PAIR2.second << endl;
 
    pair PAIR3;
     
    // Inserting Value in pair using make_pair function
    PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);
    cout << PAIR3.first << " ";
    cout << PAIR3.second << endl;
 
    pair PAIR4;
     
    // Inserting Value in pair using {}(curly brackets)
    PAIR4 = { 4, 8 };
    cout << PAIR4.first << " ";
    cout << PAIR4.second << endl;
 
    return 0;
}


C++
// C++ Code
#include 
#include 
#include 
using namespace std;
 
bool ascending_secondValue(pair a,
                           pair b)
{
    return a.second < b.second;
}
 
bool descending_firstValue(pair a,
                           pair b)
{
    return a.first > b.first;
}
 
bool descending_secondValue(pair a,
                            pair b)
{
    return a.second > b.second;
}
 
// Driver Code
int main()
{
 
    pair PAIR1[5];
    PAIR1[0] = make_pair(1, 3);
    PAIR1[1] = make_pair(13, 4);
    PAIR1[2] = make_pair(5, 12);
    PAIR1[3] = make_pair(7, 9);
   
     // Using {} to insert element instead
     // of make_pair you can use any
    PAIR1[4]
        = { 11, 2 };
 
    cout << "Sorting array in Ascending  "
            "order on the basis of First value - "
         << endl;
    sort(PAIR1, PAIR1 + 5);
    for (int i = 0; i < 5; i++) {
        cout << PAIR1[i].first << "  " << PAIR1[i].second
             << endl;
    }
 
    pair PAIR2[5];
    PAIR2[0] = make_pair(1, 3);
    PAIR2[1] = make_pair(13, 4);
    PAIR2[2] = make_pair(5, 12);
    PAIR2[3] = make_pair(7, 9);
    PAIR2[4] = make_pair(11, 2);
 
    cout << "Sorting array in Ascending  "
            " order on the basis of Second value - "
         << endl;
    sort(PAIR2, PAIR2 + 5, ascending_secondValue);
    for (int i = 0; i < 5; i++)
    {
        cout << PAIR2[i].first
              << "  " << PAIR2[i].second
             << endl;
    }
 
    pair PAIR3[5];
    PAIR3[0] = make_pair(1, 3);
    PAIR3[1] = make_pair(13, 4);
    PAIR3[2] = make_pair(5, 12);
    PAIR3[3] = make_pair(7, 9);
    PAIR3[4] = make_pair(11, 2);
 
    cout << "Sorting array in Descending order on the "
            "basis of First value - "
         << endl;
    sort(PAIR3, PAIR3 + 5, descending_firstValue);
    for (int i = 0; i < 5; i++) {
        cout << PAIR3[i].first << "  "
             << PAIR3[i].second
             << endl;
    }
 
    pair PAIR4[5];
    PAIR4[0] = make_pair(1, 3);
    PAIR4[1] = make_pair(13, 4);
    PAIR4[2] = make_pair(5, 12);
    PAIR4[3] = make_pair(7, 9);
    PAIR4[4] = make_pair(11, 2);
 
    cout << "Sorting array in Descending order on the "
            "basis of Second value - "
         << endl;
    sort(PAIR4, PAIR4 + 5, descending_secondValue);
    for (int i = 0; i < 5; i++) {
        cout << PAIR4[i].first << "  "
             << PAIR4[i].second
             << endl;
    }
 
    return 0;
}


C++
// C++ program
#include 
using namespace std;
 
// Header files, namespaces,
// macros as defined above
#include 
#include 
using namespace __gnu_pbds;
 
// ordered_set is just macro you can give any
// other name also
#define ordered_set                              \
    tree, rb_tree_tag, \
         tree_order_statistics_node_update>
 
// Driver program to test above functions
int main()
{
    // Ordered set declared with name o_set
    ordered_set o_set;
 
    // insert function to insert in
    // ordered set same as SET STL
    o_set.insert(5);
    o_set.insert(1);
    o_set.insert(2);
 
    // Finding the second smallest element
    // in the set using * because
    // find_by_order returns an iterator
    cout << *(o_set.find_by_order(1)) << endl;
 
    // Finding the number of elements
    // strictly less than k=4
    cout << o_set.order_of_key(4) << endl;
 
    // Finding the count of elements less
    // than or equal to 4 i.e. strictly less
    // than 5 if integers are present
    cout << o_set.order_of_key(5) << endl;
 
    // Deleting 2 from the set if it exists
    if (o_set.find(2) != o_set.end()) {
        o_set.erase(o_set.find(2));
    }
 
    // Now after deleting 2 from the set
    // Finding the second smallest element in the set
    cout << *(o_set.find_by_order(1)) << endl;
 
    // Finding the number of
    // elements strictly less than k=4
    cout << o_set.order_of_key(4) << endl;
 
    return 0;
}


STL 提供了一系列在各种场景中非常有用的数据结构。许多数据结构都基于现实生活中的应用程序。它是一个包含容器类、算法和迭代器的库。它是一个通用库,因此其组件是参数化的。

最常用的数据结构是:

  1. 向量
  2. 队列
  3. 优先队列
  4. 列表
  5. 有序地图
  6. 无序映射

容器或容器类存储对象和数据。总共有七个标准的“一流”容器类和三个容器适配器类,只有七个头文件提供对这些容器或容器适配器的访问。

注意:我们可以只包含一个库,即#include ,它包含所有 STL 库,但在某些比赛中,包含这个库会使代码变慢。为了克服这个问题,我们可以添加特定的库来访问STL 的特定数据结构。同样在删除元素时,需要注意数据结构是否为空。在空数据结构上调用 remove函数会导致错误。下面是一些数据结构及其插图

  1. Vector 使用数组时的主要问题是我们必须指定大小。这个缺点被向量克服了。向量在内部作为动态分配的数组工作,这是我们如何在不指定向量大小的情况下添加元素的主要原因。当向量的大小等于容量时,向量的容量增加,因此我们可以添加更多元素。

头文件:

句法:

最常用的向量函数:

  1. push_back():用于推送向量末尾的元素。要获得更快的方法,请使用 emplace_back()。
  2. pop_back():用于从向量中移除最后一个元素。
  3. size():返回向量的大小。
  4. clear():删除vector的所有内容。
  5. erase():删除指定的索引或数据。
  6. empty():如果向量为空,则返回布尔值 True,否则返回 False。
  7. Iterator lower_bound(Iterator first, Iterator last, const val):lower_bound 返回一个迭代器,该迭代器指向范围 [first, last) 中的第一个元素,该元素的值不小于 ‘val’。
  8. Iterator upper_bound(Iterator first, Iterator last, const val):upper_bound 返回一个迭代器,该迭代器指向范围 [first, last) 中的第一个元素,该元素的值大于‘val’。

C++

// C++ program to illustrate the
// function of vector in C++
#include 
 
// Header file for vector if
//  not included
#include 
using namespace std;
 
// Function to print the vector
void print(vector vec)
{
 
    // vec.size() gives the size
    // of the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
 
    cout << endl;
}
 
// Driver Code
int main()
{
    // Defining a vector
    vector vec;
 
    // Put all natural numbers
    // from 1 to 10 in vector
    for (int i = 1; i <= 10; i++) {
        vec.push_back(i);
    }
 
    cout << "Initial vector: ";
 
    // print the vector
    print(vec);
 
    // Size of vector
    cout << "Vector size: " << vec.size() << "\n";
 
    // Check of vector is empty
    if (vec.empty() == false)
        cout << "Is vector is"
             << " empty: False\n";
 
    // Popping out 10 form the vector
    vec.pop_back();
    cout << "Vector after popping: ";
    print(vec);
 
    // Deleting the first element
    // from the vector using erase()
    vec.erase(vec.begin());
    cout << "Vector after erase"
         << " first element: ";
    print(vec);
 
    // Clear the vector
    vec.clear();
    cout << "Vector after "
         << "clearing: None ";
    print(vec);
 
    // Check if vector is empty
    if (vec.empty() == true)
        cout << "Is vector is"
             << " empty: True\n";
}
输出
Initial vector: 1 2 3 4 5 6 7 8 9 10 
Vector size: 10
Is vector is empty: False
Vector after popping: 1 2 3 4 5 6 7 8 9 
Vector after erase first element: 2 3 4 5 6 7 8 9 
Vector after clearing: None 
Is vector is empty: True

2.堆栈它是后进先出(LIFO)数据结构。它可以使用数组、链表和向量来实现。一些问题,如反转元素或字符串、括号检查、打印下一个更大的元素、后缀表达式等,可以使用堆栈类来完成,而不是让我们可以使用其内置函数的所有函数。
头文件:

句法:

最常用的堆栈函数:

  1. push():用于将元素压入栈顶。
  2. pop():删除栈顶元素但不返回。
  3. top():返回栈顶元素。
  4. empty(): 返回布尔值,即如果栈为空则返回真,否则返回假。
  5. size():返回堆栈的大小。

C++

// C++ program to illustrate the
// function of stack in C++
#include 
 
// Header file for stack
#include 
using namespace std;
 
// Function to print the stack
void print(stack s)
{
 
    // Loops runs till stack
    // becomes empty
    while (s.empty() == false) {
 
        // Prints the top element
        cout << s.top() << " ";
 
        // Now pops the same top element
        s.pop();
    }
 
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Given char array
    char array[]
        = { 'G', 'E', 'E', 'K',
            'S', 'F', 'O', 'R', 'G',
            'E', 'E', 'K', 'S' };
 
    // Defining stack
    stack s;
 
    // Check if stack is empty
    if (s.empty() == true) {
        cout << "Stack is currently Empty"
            << "\n";
    }
    else {
        cout << "Stack is not empty"
            << "\n";
    }
 
    // Push elements in stack
    for (int i = sizeof(array) / sizeof(array[0]) - 1;
        i >= 0; i--) {
        s.push(array[i]);
    }
 
    // Size of stack
    cout << "Size of stack: "
        << s.size() << "\n";
 
    // Content of stack
    cout << "Stack initially: ";
    print(s);
 
    // Returning the top
    // element of the stack
    cout << "Top element: "
        << s.top() << "\n";
 
    // Popping the top
    // element in stack
    s.pop();
 
    cout << "Stack after 1"
        << "pop operation: ";
    print(s);
 
    // Now checking the top element
    cout << "Top element after popping: "
        << s.top() << "\n";
 
    // Size of stack
    cout << "Size of stack"
        << "after popping: "
        << s.size() << "\n";
 
    // Again checking if the
    // stack is empty
    if (s.empty() == true) {
        cout << "Stack is currently Empty"
            << "\n";
    }
    else {
        cout << "Stack is not empty"
            << "\n";
    }
    return 0;
}
输出
Stack is currently Empty
Size of stack: 13
Stack initially: G E E K S F O R G E E K S 
Top element: G
Stack after 1pop operation: E E K S F O R G E E K S 
Top element after popping: E
Size of stackafter popping: 12
Stack is not empty

3.队列它是先进先出(FIFO)的数据结构。我们之所以要求队列使用了很多先进先出的实际应用,当数据不需要提前处理时。例如,在购买演出门票的队列中,最先进入队列的人将首先获得门票。它可以像堆栈一样使用数组、链表和向量来实现。队列的一些应用包括树和图中的层序遍历、资源共享等。
头文件:

句法:

队列最常用的函数:

  1. push():用于推送队列后面的元素
  2. pop():删除队列最前面的元素但不返回。
  3. front():返回队列的最前面元素,或行中的第一个元素。
  4. empty():返回布尔值,即如果队列为空则返回真,否则返回假
  5. back():返回队列的最后一个元素。
  6. size():返回队列的大小。

C++

// C++ program to illustrate the
// function of vector in C++
#include 
 
// Header file for queue
#include 
using namespace std;
 
// Function to print the queue
void print(queue q)
{
    for (int i = 0; i < q.size(); i++) {
 
        // Printing the front element
        cout << q.front() << " ";
 
        // Popping the front element
        q.pop();
    }
 
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Given array
    char array[]
        = { 'G', 'E', 'E', 'K', 'S' };
 
    // Defining queue
    queue q;
 
    if (q.empty() == true) {
        cout << "Queue is empty\n";
    }
 
    for (int i = 0; i < 5; i++) {
        q.push(array[i]);
    }
 
    cout << "Queue Initially: ";
    print(q);
 
    // Front element
    cout << "Front element: "
        << q.front() << "\n";
 
    // Back element
    cout << "Back Element: "
        << q.back() << "\n";
 
    // Size of queue
    cout << "Size of queue: "
        << q.size() << "\n";
 
    // Empty
    if (q.empty() == false) {
        cout << "Queue is not empty\n";
    }
    return 0;
}
输出
Queue is empty
Queue Initally: G E E 
Front element: G
Back Element: S
Size of queue: 5
Queue is not empty

4.Priority Queue 这个数据结构类似于队列,但是先出的顺序是由用户设置的优先级决定的。主要功能包括获取最高优先级元素、插入、删除最高优先级元素或降低优先级。数据结构使用Heaps而不是BST,因为在BST中,创建树的成本比堆高,堆的复杂度更好。此外,堆提供完全二叉树和堆顺序属性,满足优先队列的所有属性。 Priority Queue 有两种变体,Min Heap 和 Max Heap。
可以轻松实现诸如查找 k 个最大或最小元素、合并 k 个未排序数组、Dijkstra 最短路径算法、用于压缩的霍夫曼代码、Prim 算法等复杂问题。
头文件:

句法:

优先队列最常用的函数:

  1. push():用于推送队列中的元素
  2. pop():删除队列的最高优先级元素但不返回。删除最大堆中具有最大优先级的元素,否则删除最小元素
  3. size():返回队列的大小。
  4. empty():返回布尔值,即如果队列为空则返回真,否则返回假。
  5. top():返回队列的顶部元素。在最大优先级队列中,它返回最大值,而在最小优先级队列中,它返回最小值。

C++

// C++ program to illustrate the
// function of priority queue in C++
#include 
 
// Header file for priority
// queue, both MIN and MAX
#include 
using namespace std;
 
// Function to print the
// min priority queue
void print_min(
    priority_queue, greater > q)
{
    while (q.empty() == false)
    {
        // Print the front
        // element(MINIMUM)
        cout << q.top() << " ";
 
        // Pop the minimum
        q.pop();
    }
    cout << "\n";
}
 
// Function to print the
// min priority queue
void print_max(priority_queue q)
{
    while (q.empty() == false)
    {
        // Print the front
        // element(MAXIMUM)
        cout << q.top() << " ";
 
        // Pop the maximum
        q.pop();
    }
    cout << "\n";
}
 
// Driver Code
int main()
{
    // MIN priority queue
    priority_queue max_pq;
 
    // MAX priority_queue
    priority_queue, greater > min_pq;
 
    // Is queue empty
    if (min_pq.empty() == true)
        cout << "MIN priority "
             << "queue is empty\n";
 
    if (max_pq.empty() == true)
        cout << "MAX priority"
             << " queue is empty\n";
 
    cout << "\n";
 
    for (int i = 1; i <= 10; i++)
    {
        min_pq.push(i);
        max_pq.push(i);
    }
 
    cout << "MIN priority queue: ";
    print_min(min_pq);
 
    cout << "MAX priority queue: ";
    print_max(max_pq);
    cout << "\n";
 
    // Size
    cout << "Size of min pq: " << min_pq.size() << "\n";
    cout << "Size of max pq: " << max_pq.size() << "\n";
    cout << "\n";
 
    // Top element
    cout << "Top of min pq: " << min_pq.top() << "\n";
    cout << "Top of max pq: " << max_pq.top() << "\n";
    cout << "\n";
 
    // Pop the front element
    min_pq.pop();
    max_pq.pop();
 
    // Queus after popping
    cout << "MIN priority "
         << "queue after pop: ";
    print_min(min_pq);
    cout << "MAX priority "
         << "queue after pop: ";
    print_max(max_pq);
    cout << "\n";
 
    // Size after popping
    cout << "Size of min pq: " << min_pq.size() << "\n";
    cout << "Size of max pq: " << max_pq.size() << "\n";
    cout << "\n";
 
    // Is queue empty
    if (min_pq.empty() == false)
        cout << "MIN priority "
             << " queue is not empty\n";
 
    if (max_pq.empty() == false)
        cout << "MAX priority queue"
             << " is not empty\n";
}
输出
MIN priority queue is empty
MAX priority queue is empty

MIN priority queue: 1 2 3 4 5 6 7 8 9 10 
MAX priority queue: 10 9 8 7 6 5 4 3 2 1 

Size of min pq: 10
Size of max pq: 10

Top of min pq: 1
Top of max pq: 10

MIN priority queue after pop: 2 3 4 5 6 7 8 9 10 
MAX priority queue after pop: 9 8 7 6 5 4 3 2 1 

Size of min pq: 9
Size of max pq: 9

MIN priority  queue is not empty
MAX priority queue is not empty

4.Set 集合是关联容器,其中每个元素都是唯一的。元素一旦插入集合中就不能修改。集合忽略重复值,所有元素都按排序顺序存储。当需要对传入元素进行排序且不需要修改时,此数据结构特别有用。
集合可以按两种顺序存储元素,升序或降序。
头文件:

句法:

Set 最常用的函数:

  1. insert():该函数用于在Set中插入一个新元素。
  2. begin():这个函数返回一个迭代器到集合中的第一个元素。
  3. end():它返回一个迭代器,指向集合中最后一个元素之后的理论元素。
  4. size():返回集合的总大小。
  5. find():如果存在,它返回一个迭代器到搜索元素。如果没有,它会给出一个迭代器到最后。
  6. count():返回集合中出现的次数。如果存在则为 1,否则为 0。
  7. empty():返回布尔值,即如果为空则为真否则为假。

5.列表列表以非连续方式存储数据。列表的元素可以分散在不同的内存块中。访问任何特定索引变得昂贵,因为必须完成从已知索引到该特定索引的遍历,因此它比向量慢。零大小的列表也是有效的。
头文件:

句法:

最常用的函数列表:

  1. push_front(element):在列表的开头插入一个新元素“元素”。
  2. push_back(element) :在列表的末尾插入一个新元素“元素”。
  3. pop_front():移除列表的第一个元素。
  4. pop_back():删除列表的最后一个元素。
  5. front() :返回列表中第一个元素的值。
  6. back() :返回列表中最后一个元素的值。
  7. empty():返回布尔值,即如果为空则为真否则为假。

6.Unordered Maps 假设你有一个铅笔盒和一些钢笔。你在盒子里放了一些笔,这将是随机的,不像有序地图那样有序,但你可以访问任何笔并使用它。无序映射也是如此,元素随机存储,但您可以随时访问任何顺序。有序映射和无序映射之间的主要区别在于编译器存储它们的方式。它有两个参数,第一个称为KEY ,另一个称为Value 。键映射到值并且始终是唯一的。

头文件:

句法:

无序映射最常见的函数:

  1. count():返回布尔值,即如果传递的键存在则返回 1,否则返回 false。
  2. erase(key) :返回传递的密钥。
  3. clear() :删除整个地图。
  4. size() :返回地图的大小。

7.Ordered Maps:假设你的房间里有一个新书架和一些书。您将书籍一个接一个地排列,但在排列任意数量的书籍后,您可以按任意顺序访问已排列的书籍,并在阅读后将书籍保存在同一位置。这是地图的一个例子。您按顺序一个接一个地填充值,并且顺序始终保持不变,但您可以随时访问任何元素。这个数据结构也是使用动态数组实现的。与无序映射一样,它有两个参数,第一个称为KEY ,另一个称为Value 。键映射到值并且始终是唯一的。

头文件:

句法:

有序映射最常用的函数:

  1. count() :返回布尔值,即,如果密钥传递存在,则返回 1,否则返回 false。
  2. 擦除(密钥):返回传递的密钥。
  3. clear():删除整个地图。
  4. size():返回地图的大小

其他有用的 STL 是 –

1.) Pair : pair 容器是在 标头中定义的简单容器,由两个数据元素或对象组成。第一个元素被称为“第一”,第二个元素被称为“第二”,并且顺序是固定的(第一,第二)。 Pair 用于将两个类型可能不同的值组合在一起。 Pair 提供了一种将两个异构对象存储为一个单元的方法。可以分配、复制和比较对。在 map 或 hash_map 中分配的对象数组默认为“pair”类型,其中所有“first”元素都是与其“second”值对象关联的唯一键。要访问元素,我们使用变量名,后跟点运算符,后跟关键字 first 或 second。

头文件:

#include 

句法 :

pair (data_type1, data_type2) Pair_name;

Pair 最常见的函数:

  1. make_pair() 此模板函数允许创建一个值对,而无需明确写入类型。

以下是实现上述函数的代码: –

C++

// C++ code
#include 
#include 
using namespace std;
 
int main()
{
    // Declaring the PAIR1 of int and char
    // IF pair is not initialized then ,
    // default value of int/double is 0
    // and for string/char it is NULL
    pair PAIR1;
    cout << PAIR1.first << " ";
   
    // NULL value therefore, not displayed
    cout << PAIR1.second
         << endl;
 
    // Initializing the pair during it's Declaration
    pair PAIR2("GeeksForGeeks", 1.23);
    cout << PAIR2.first << " ";
    cout << PAIR2.second << endl;
 
    pair PAIR3;
     
    // Inserting Value in pair using make_pair function
    PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);
    cout << PAIR3.first << " ";
    cout << PAIR3.second << endl;
 
    pair PAIR4;
     
    // Inserting Value in pair using {}(curly brackets)
    PAIR4 = { 4, 8 };
    cout << PAIR4.first << " ";
    cout << PAIR4.second << endl;
 
    return 0;
}

如果有对的阵列,并且使用内置的排序函数然后,默认排序根据第一值中的每个元素。为了按降序排序的阵列的基础上(即obj.first)对数组传递函数你想对数组进行排序。

下面的代码将展示如何对数组进行排序: –

C++

// C++ Code
#include 
#include 
#include 
using namespace std;
 
bool ascending_secondValue(pair a,
                           pair b)
{
    return a.second < b.second;
}
 
bool descending_firstValue(pair a,
                           pair b)
{
    return a.first > b.first;
}
 
bool descending_secondValue(pair a,
                            pair b)
{
    return a.second > b.second;
}
 
// Driver Code
int main()
{
 
    pair PAIR1[5];
    PAIR1[0] = make_pair(1, 3);
    PAIR1[1] = make_pair(13, 4);
    PAIR1[2] = make_pair(5, 12);
    PAIR1[3] = make_pair(7, 9);
   
     // Using {} to insert element instead
     // of make_pair you can use any
    PAIR1[4]
        = { 11, 2 };
 
    cout << "Sorting array in Ascending  "
            "order on the basis of First value - "
         << endl;
    sort(PAIR1, PAIR1 + 5);
    for (int i = 0; i < 5; i++) {
        cout << PAIR1[i].first << "  " << PAIR1[i].second
             << endl;
    }
 
    pair PAIR2[5];
    PAIR2[0] = make_pair(1, 3);
    PAIR2[1] = make_pair(13, 4);
    PAIR2[2] = make_pair(5, 12);
    PAIR2[3] = make_pair(7, 9);
    PAIR2[4] = make_pair(11, 2);
 
    cout << "Sorting array in Ascending  "
            " order on the basis of Second value - "
         << endl;
    sort(PAIR2, PAIR2 + 5, ascending_secondValue);
    for (int i = 0; i < 5; i++)
    {
        cout << PAIR2[i].first
              << "  " << PAIR2[i].second
             << endl;
    }
 
    pair PAIR3[5];
    PAIR3[0] = make_pair(1, 3);
    PAIR3[1] = make_pair(13, 4);
    PAIR3[2] = make_pair(5, 12);
    PAIR3[3] = make_pair(7, 9);
    PAIR3[4] = make_pair(11, 2);
 
    cout << "Sorting array in Descending order on the "
            "basis of First value - "
         << endl;
    sort(PAIR3, PAIR3 + 5, descending_firstValue);
    for (int i = 0; i < 5; i++) {
        cout << PAIR3[i].first << "  "
             << PAIR3[i].second
             << endl;
    }
 
    pair PAIR4[5];
    PAIR4[0] = make_pair(1, 3);
    PAIR4[1] = make_pair(13, 4);
    PAIR4[2] = make_pair(5, 12);
    PAIR4[3] = make_pair(7, 9);
    PAIR4[4] = make_pair(11, 2);
 
    cout << "Sorting array in Descending order on the "
            "basis of Second value - "
         << endl;
    sort(PAIR4, PAIR4 + 5, descending_secondValue);
    for (int i = 0; i < 5; i++) {
        cout << PAIR4[i].first << "  "
             << PAIR4[i].second
             << endl;
    }
 
    return 0;
}

有序集:有序集是 g++ 中基于策略的数据结构,它使唯一元素按排序顺序排列。它以 log(n) 复杂度执行STL 中set数据结构执行的所有操作,并以 log(n) 复杂度执行两个额外的操作

  1. order_of_key (k) :严格小于 k 的项目数。
  2. find_by_order(k) :集合中的第 K 个元素(从零开始计数)。

头文件和命名空间:-

#include  
#include  
using namespace __gnu_pbds; 

有序集实现所需的必要结构是:

tree < int ,  null_type ,  less ,  rb_tree_tag ,  tree_order_statistics_node_update >

您可以在此处详细了解它们。

有序集合中除集合之外的附加函数是——

  1. find_by_order(k):它在 O(log n) 时间内返回到集合中第 k 个元素(从零开始计数)的迭代器。要找到第一个元素 k 必须为零。

让我们假设我们有一个集合 s :{1, 5, 6, 17, 88},然后:

*(s.find_by_order(2)) : 集合中的第三个元素,即 6

*(s.find_by_order(4)) :集合中的第 5 个元素,即 88

2. order_of_key(k) :它返回在 O(log n) 时间内严格小于我们的项目 k 的项目数。

让我们假设我们有一个集合 s :{1, 5, 6, 17, 88},然后:

s.order_of_key(6) :严格小于 6 的元素计数为 2。

s.order_of_key(25) :严格小于 25 的元素计数为 4。

NOTE :  ordered_set is used here as a macro given to 
    tree. 
    Therefore it can be given any name as macro other than ordered_set
     but generally in the world of competitive programming it is commonly referred as ordered set 
     as it is a set with additional operations.

C++

// C++ program
#include 
using namespace std;
 
// Header files, namespaces,
// macros as defined above
#include 
#include 
using namespace __gnu_pbds;
 
// ordered_set is just macro you can give any
// other name also
#define ordered_set                              \
    tree, rb_tree_tag, \
         tree_order_statistics_node_update>
 
// Driver program to test above functions
int main()
{
    // Ordered set declared with name o_set
    ordered_set o_set;
 
    // insert function to insert in
    // ordered set same as SET STL
    o_set.insert(5);
    o_set.insert(1);
    o_set.insert(2);
 
    // Finding the second smallest element
    // in the set using * because
    // find_by_order returns an iterator
    cout << *(o_set.find_by_order(1)) << endl;
 
    // Finding the number of elements
    // strictly less than k=4
    cout << o_set.order_of_key(4) << endl;
 
    // Finding the count of elements less
    // than or equal to 4 i.e. strictly less
    // than 5 if integers are present
    cout << o_set.order_of_key(5) << endl;
 
    // Deleting 2 from the set if it exists
    if (o_set.find(2) != o_set.end()) {
        o_set.erase(o_set.find(2));
    }
 
    // Now after deleting 2 from the set
    // Finding the second smallest element in the set
    cout << *(o_set.find_by_order(1)) << endl;
 
    // Finding the number of
    // elements strictly less than k=4
    cout << o_set.order_of_key(4) << endl;
 
    return 0;
}
输出
2
2
2
5
1
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程