美文网首页
C++常用数据结构操作示例

C++常用数据结构操作示例

作者: iamlightsmile | 来源:发表于2020-04-30 11:34 被阅读0次

    0. 前言

    由于自己使用Python居多,对C++并不太熟悉,但是最近在刷算法题,所以这里简单整理总结一下C++常用数据结构的操作函数,以便方便查阅检索。

    1. C++标准库常用数据结构

    常用数据结构如下:

    • string
    • vector
    • list
    • queue和priority_queue
    • set
    • map
    • stack

    2. 常用数据结构操作示例

    1. string

        //header file : <string>
    
         //declaration
        string s = "hello world!";
    
        // visit by subscript
        char c = s[2];//l
        const char cc = s.at(6);//w
    
        // get the length of the string
        int length = s.length();//12
        int size = s.size();//12
    
        // the string is empty or not
        bool is_empty = s.empty();//0
    
        // concat strings
        string t = "c++";
        s.append(t);//hello world!c++
        s += "Python!";//hello world!c++Python!
    
        // get substring
        string sub_str = s.substr(0, 5);//hello
    
        // find substring
        int pos = s.find("world");//6
    
        // insert operation
        s.insert(0, "Hi!");//Hi!hello world!c++Python!
    
        // compare operation
        string other = "NLP";
        bool cmp = other < s;//0
    
        // visit element by iterator
        for (auto i: s) {
            cout << i << endl;
        }
    

    2. vector

        // header file :<vector>
    
        // declaration
        vector<int> vec {2, 3, 4}; //[2, 3, 4]
    
        // size of vector
        int size = vec.size(); //3
    
        // the vector is empty or not
        bool is_empty = vec.empty(); // 0
    
        // visit by subscript
        auto e = vec.at(2);//4
        int m = vec[1];//3
        cout << e << m << endl;
    
        // append element at back
        vec.push_back(5); // [2, 3, 4, 5]
    
        // delete the last element
        vec.pop_back();//[2, 3, 4]
    
        // insert an element by iterator
        vec.insert(vec.begin(), 1); //[1, 2, 3, 4]
    
        // visit the first element and the last element
        cout << vec.front() << vec.back() << endl; // 14
    
        // visit by iterator
        auto iter = vec.begin();
        while (iter != vec.end()) {
            cout << *iter << endl;
            iter += 1;
        }
    
        // delete element by iterator
        auto item = vec.erase(vec.end() -2);
    
        cout << *item << endl;//4
    
        for (auto i: vec) {
            cout << i << endl;
        }
    

    参考:

    相关文章

      网友评论

          本文标题:C++常用数据结构操作示例

          本文链接:https://www.haomeiwen.com/subject/juiawhtx.html