Understanding C++: STL

Overview

Reference connection

STL is a subset of std

  • STL (Standard Template Library), the standard template library
  • An important feature of STL is the separation of data structure and algorithm . For example, since the sort() function of STL is completely universal, you can use it to manipulate almost any data collection, including linked lists, containers and arrays;
  • Another important feature of STL is that it is not object-oriented. In order to be sufficiently versatile, STL mainly relies on templates .

Six major components in STL:

  1. Container (Container) is a kind of data structure, such as list, vector, and deques, provided by the method of template class. In order to access the data in the container, you can use the iterator output by the container class;

  2. Iterator provides a way to access objects in the container. For example, you can use a pair of iterators to specify a range of objects in a list or vector. An iterator is like a pointer. In fact, C++ pointers are also an iterator. However, iterators can also be class objects that define operator*() and other pointer-like operators;

  3. Algorithm (Algorithm) is a template function used to manipulate data in the container. For example, STL uses sort() to sort the data in a vector, and find() to search for objects in a list. The functions themselves have nothing to do with the structure and type of the data they operate on, so they can range from simple arrays to Use on any data structure of highly complex containers;

  4. Functor

  5. Adaptor

  6. Allocator

container

Sequence container: Vector; Deque; List;

Associative container: Map/Multimap; Set/Multiset

Understanding: vector

Dynamic array

List is a doubly linked list implemented by stl. Compared with vectors, it allows fast insertion and deletion, but random access is slower.

**List does not support random access, so the efficiency of accessing elements is low, **list does not have at and subscript operators

push_back & pop_back: add and delete at the end of the container

#include <string.h>
#include <vector>
#include <iostream>
#include <algorithm>//sort算法包含
using namespace std;
int main()
{
    
    
    vector<int>obj;//创建一个向量存储容器 int
    /**********push_back*****/
    for(int i=0;i<10;i++) // push_back(elem)在数组最后添加数据
    {
    
    
        obj.push_back(i);
        cout<<obj[i]<<",";    
    }
    cout<<endl;
    /**********pop_back*****/
    for(int i=0;i<5;i++)//去掉数组最后一个数据
    {
    
    
        obj.pop_back();
    }
    for(int i=0;i<obj.size();i++)//size()容器中实际数据个数
    {
    
    
        cout<<obj[i]<<",";
    }
    cout<<endl;
    /**********sort&reverse*****/
    obj.push_back(100);obj.push_back(-9);obj.push_back(20);
    sort(obj.begin(),obj.end());//默认升序,也可以改变sort的定义如:sort(begin,end,compare)
    vector<int>::iterator iter;
    reverse(obj.begin(),obj.end());//只是改变方向,它不是排序
    for(iter=obj.begin();iter!=obj.end();iter++)
    {
    
    
        cout<<*iter<<",";
    }
    cout<<endl;
    /****at形式访问*******/
    cout<<obj.at(2)<<endl;//at形式访问
    obj.clear();//清空
    cout<<"size:"<<obj.size();//size为0;
    return 0;
}

Understanding: List

Reference connection

Understanding: Map

The map in C++ provides a container of key-value pairs . The data in it appears in pairs, as shown in the figure below: the first value in each pair is called a key, and each keyword can only Occurs once in the map; the second is called the corresponding value of the key.

A red-black tree (a non-strictly balanced binary tree) is built inside the map. This tree has the function of automatically sorting data, so all the data in the map is in order .

Both map and multimap need #include,唯一的不同是,map的键值key不可重复,而multimap可以,也正是由于这种区别,map支持[ ]运算符,multimap不支持[ ]运算符。在用法上没什么区别。


pair

It is also in std (vector, list, and map are also in std) , but there are applications in map, so let's talk about it first.

Reference connection

The standard library type-pair type is defined in the #include header file and is defined as follows:

(It seems that both utility and iostream can be used. Why is this?? )

Class template: template<class T1,class T2> struct pair

Parameters: T1 is the data type of the first value, T2 is the data type of the second value.

Function: pair combines a pair of values ​​(T1 and T2) into one value. This pair of values ​​can have different data types (T1 and T2). The two values ​​can be accessed by the two public functions of pair, first and second, respectively.

Define the constructor

pair<T1, T2> p1; //Create an empty pair object (using the default construction), its two elements are of type T1 and T2, and are initialized by value.

pair<T1, T2> p1(v1, v2); //Create a pair object. Its two elements are of type T1 and T2 respectively. The first member is initialized to v1 and the second member is initialized to v2.

make_pair(v1, v2); // Create a new pair object with the values ​​of v1 and v2, whose element types are v1 and v2 respectively.

p1 <p2; // The less than operation between two pair objects is defined in dictionary order: such as p1.first <p2.first or! (p2.first <p1.first) && (p1.second <p2.second) It returns true.

p1 == p2; // If the first and second of two objects are equal in turn, the two objects are equal; this operation uses the element == operator.

p1.first; // Return the public data member named first in the object p1

p1.second; // Return the public data member named second in the object p1

E.g:

pair<string, string> anon; // 创建一个空对象anon,两个元素类型都是string
pair<string, int> word_count; // 创建一个空对象 word_count, 两个元素类型分别是string和int类型
pair<string, vector<int> > line; // 创建一个空对象line,两个元素类型分别是string和vector类型
//下面是定义的时候初始化
pair<string, string> author("James","Joy"); // 创建一个author对象,两个元素类型分别为string类型,并默认初始值为James和Joy。
pair<string, int> name_age("Tom", 18);

Code:

tie reference connection

#include<iostream>
#include <tuple>//用于包含tie,std:Ltie
using namespace std;
//std::pair  std::tie
std::pair<std::string, int> getPreson() {
    
    
    return std::make_pair("Sven", 25);
}//这个是函数,返回值为pair类型
int main()
{
    
    
    /********访问***************/
    pair<int ,double> p1;
    p1.first = 1;
    p1.second = 2.5;
    cout<<p1.first<<' '<<p1.second<<endl;
    /*****利用make_pair创建新的pair对象**/
    pair<int, double> p3;
    p3 = make_pair(1, 1.2);
    cout << p3.first << p3.second << endl;
    /*****通过std::tie获取pair元素值***/
    string name;
    int ages;
    tie(name, ages) = getPreson();
    cout << "name: " << name << ", ages: " << ages << endl;
}

map

The elements in the map are automatically sorted by Key in ascending order, so the sort function cannot be used on the map;

Code understanding:

#include <map>    
#include <string>  
#include <iostream>  
using namespace std;  
  
int main()  
{
    
      
    map<int, string> mapStudent =
    {
    
    
        {
    
    0,"student_zero"}
    }; //初始化
    std::pair<map<int, string>::iterator, bool> ret;
    
    mapStudent[1] = "student_one";//数组插入
    ret = mapStudent.insert(pair<int, string>(1, "student_two")); //pair插入,并返回是否插入成功
    mapStudent.insert(map<int, string>::value_type (2, "student_two"));//value_type插入
    map<int, string>::iterator iter;  //迭代器访问
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
       cout<<iter->first<<' '<<iter->second<<endl;  
    
    if(!mapStudent.empty())
    {
    
    
        cout<<"size:"<<mapStudent.size()<<endl;//map的大小
        cout<<"max_size:"<<mapStudent.max_size()<<endl;//最多存多少,和内存有关?
        cout<<"map count"<<mapStudent.count(3)<<endl;//查找key的value个数,map非0即1
    }
    /********find*****/
    iter = mapStudent.find(1);
    cout<<"find num 1:"<<iter->second<<endl;
    /*****erase*****/
    map<int, string>::iterator iter_1;  //迭代器访问
    iter_1 = mapStudent.erase(iter);
    cout<<"iter:"<<iter->second<<endl;//原来的迭代器还在指向
    cout<<"num 1:"<<iter_1->second<<endl<<endl;
    
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
       cout<<iter->first<<' '<<iter->second<<endl;
}

Guess you like

Origin blog.csdn.net/QLeelq/article/details/111059293