티스토리 뷰

C++

Vector & List in C++

seoca 2018. 11. 22. 14:17



Vector & List


Vector
Items are stored in contiguous memory and assigned their own slots. Each item in Vector can be accessed by index and new items can be inserted at the end or in the middle.
Vector automatically deletes [] to prevent memory leaks. 



Syntax for Vector

vector<type> variable_name (number of elements);



List
List can be inserted and deleted at every position.
If insertion and deletion are frequent, List is more advantageous than Vector.
One node in the list has its own value and the address of the next list. (Non-contiguous memory).




Syntax for List

list<type> variable_name;



Example code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main() {
    vector<int> vec_arr = { 1,2,3 };
 
    for (auto &itr : vec_arr) //Auto type deduction in range-based for loop
        cout << itr << " "// 1 2 3
    cout << endl;
 
    cout << vec_arr[1<< endl// 2
    cout << vec_arr.at(1<< endl// 2 
    cout << vec_arr.size() << endl// 3
    
    vec_arr.resize(5);
    vec_arr.push_back(3);
 
    for (auto &itr : vec_arr) 
        cout << itr << " "// 1 2 3 0 0 3
    cout << endl;
 
    list<int> list;
    list.push_back(5);
    list.push_front(3);
 
    for (auto &itr2 : list)
        cout << itr2 << " "// 3 5
    cout << endl;
 
    return 0;
}
cs


'C++' 카테고리의 다른 글

Virtual Function in C++  (0) 2018.11.22
Friend in C++  (0) 2018.11.22
Templates (Function Template & Class Template) in C++  (0) 2018.11.10
Exception handling (Try Throw and Catch) in C++  (0) 2018.11.09
Inline function in C++  (0) 2018.11.09