ไลบรารีแม่แบบมาตรฐานของภาษาซีพลัสพลัส/vector

จาก testwiki
รุ่นแก้ไขเมื่อ 17:28, 23 มีนาคม 2567 โดย imported>Minorax
(ต่าง) ←รุ่นแก้ไขก่อนหน้า | รุ่นแก้ไขล่าสุด (ต่าง) | รุ่นแก้ไขถัดไป→ (ต่าง)
ไปยังการนำทาง ไปยังการค้นหา

vector เป็น array ที่สามารถเพิ่มขนาดได้ มีความสามารถ random access และสามารถดำเนินการกับข้อมูลด้านปลายได้ในเวลาคงที่

หากได้อ่าน [[../deque|deque]] มาแล้ว จะเห็นได้ว่า vector มีความสามารถด้อยกว่า เนื่องจาก deque มีความสามารถเหมือน vector ทุกประการ แต่สามารถเพิ่ม/ลบข้อมูลทางด้านหน้าได้ด้วย อย่างไรก็ตาม หากโปรแกรมที่จะเขียนไม่ได้มีการดำเนินการกับข้อมูลด้านหน้าก็จะนิยมใช้ vector มากกว่า เนื่องจากในทางปฏิบัติ deque จะใช้พื้นที่มากกว่า vector

การใช้งานและการประกาศตัวแปร

ต้องนำเข้า header file "vector" โดย #include <vector>

ให้ T คือชนิดข้อมูลใดๆ และ var คือชื่อตัวแปร มีรูปแบบการประกาศตัวแปร vector โดย vector <T> var;

method

push_back

แม่แบบ:STLdata

pop_back

แม่แบบ:STLdata

front

แม่แบบ:STLdata

back

แม่แบบ:STLdata

size

แม่แบบ:STLdata

empty

แม่แบบ:STLdata

operator

[]

แม่แบบ:STLdata

ตัวอย่างโค้ด

#include <cstdio>
#include <vector>

using namespace std;

struct ST{
    int a, b;
};

int main(){
    vector <int> V;                        // []
    V.push_back(13);                       // [13]
    V.push_back(12);                       // [13,12]
    V.pop_back();                          // [13]
    V.push_back(5);                        // [13,5]
    
    printf("%d", V.back());                // => 5
    printf("%d", V.front());               // => 13
    
    for(int i = 0; i < 4; i++)
        V.push_back(i);                    // [13,5,0,1,2,3]
    
    for(int i = 0; i < (int)V.size(); i++)
        printf("%d ", V[i]);               // => 13 5 0 1 2 3
                                        
    while(not V.empty()) V.pop_back();     // []
                                        
    V.pop_back()                           // => Error
    V.front()                              // => Error
    V.back()                               // => Error
                                        
    ST tmp;                                
    vector <ST> T;                         // []
                                        
    tmp.a = 5;                             
    tmp.b = 3;                             
                                        
    T.push_back(tmp);                      // [(5,3)]
                                        
    printf("%d\n", T.front().b);           // => 3
    
    return 0;
}

แม่แบบ:TODO

สารบัญ

แม่แบบ:Stage short stack
แม่แบบ:Stage short queue
แม่แบบ:Stage short priority_queue
แม่แบบ:Stage short deque
แม่แบบ:Stage short vector
แม่แบบ:Stage short map
แม่แบบ:Stage short set