-
Notifications
You must be signed in to change notification settings - Fork 0
/
54-vector-stl.cpp
66 lines (48 loc) · 1.84 KB
/
54-vector-stl.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
void myPrinter(vector<int> v){
int size = v.size(); // That's how we get size of a vector object in c++.
cout << "Vector Array: [ ";
for (int i = 0; i < size; i++){
cout << v[i] << " ";
}
cout << "]";
cout << endl;
cout << "Size: " << size << " | Capacity: " << v.capacity() << endl;
(size > 0) ? (cout << "Front element: " << v.front()) : cout << ""; // or v[0]
(size > 0) ? (cout << " | Back element: " << v.back()) : cout << ""; // or v[size - 1]
cout << "\n--------------------\n";
return;
}
// vector is dynamically sized array in c++.
// it can increase / shrink its size dynamically as we add / remove elements in it.
// it doubles its capacity, everytime its full, and we push a new element in it.
int main(){
vector<int> myVector; //no need to specify the size. only specify the type of elements.
myVector.push_back(10);myVector.push_back(20);myVector.push_back(50);
myPrinter(myVector);
// for deleting the last element:
myVector.pop_back();
myPrinter(myVector);
// for deleting all the elements of vector:
myVector.clear();
myPrinter(myVector);
// For-Each method of printing a vector :
vector<int> vec2 = {1,5,9,11,64};
cout << "Second vector: ";
for(auto elem : vec2){
cout << elem << " ";
}
// Using builtin custum iterator for the vector
vector<int>::iterator myIterator;
cout << endl << "printing using custom iterator: " ;
for (myIterator = vec2.begin(); myIterator != vec2.end(); myIterator++){
cout << *myIterator << " " ;
}
cout << "\n--------------------------\n";
// for initializing a vector with initial size and default value for each item:
vector<int> vec3(10,108);
myPrinter(vec3);
return 0;
}