c++ vector
Vector is like array.In array, you cannot change the length, but you can do that in vector.
It has index like array. syntax like "vector[3]= 3" is totally fine in vector
Format
std :: vector
-> if you use "using namespace std", you do tno need to add "std ::"
constructor
vector <type> name
vector <type> name (length, val)
vector <type> name (array , size of array)
- type can be anything(string, int, char and other )
.size()
- return size of vector
.insert( "interator", "val" )
- add new element to vector. The element would be added at index. The elements in the vector shift one to right
- you need iterator vector<int>::iterator
.push_back( "val" )
- add new element to vector. The element will be stored at the end of vector.
.erase( "iterator" )
- delete element of vector
- if your vector is called input3, treat input3.begin() as index 0
-> if you want to delete third element of vector, it would be input3.begin() +2
- once the element is deleted, elements after deleted elements would shift one to left
.clear()
- delete all element of vector
------------------------------------------------------------------------------------------------------------------------
The following is practice code. If you have suggestion or correction, please feel free to leave comment.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
int array[] = {1,2,3,4};
//1
//constructors of vector
vector <int> input (3,100); //length = 3 val = 100
vector <int> input2 (array, array + sizeof(array) / sizeof(int));// constructor with array
vector <int> input3;// empty vector
//2
//print element of vector. it is like array
for(int i=0; i< input.size(); i++){
cout << input[i] << endl;
}
cout << "----------------------------" << endl;
//3
//print element of vector. it is like array
for(int i=0; i< input2.size(); i++){
cout << input2[i] << endl;
}
cout << "----------------------------" << endl;
//3
//insert elements to vector
//if you use insert, the vector element is stored at the very first index. the rest
//are shift to right by one
//if you use push_back, the vector element is stored at the end of vector
vector<int>::iterator it;
it = input3.insert(it , 300);
it = input3.insert(it , 400);
it = input3.insert(it , 100);
input3.push_back( 999 );
for (int i=0; i<input3.size(); i++){
cout << input3[i] << endl;
}
cout << "----------------------------" << endl;
//4
//delete 2 elements of input3 vector
//index(int) wont work. you need to use either begin or iterator
input3.erase (input3.begin()+1);
for (int i=0; i<input3.size(); i++){
cout << input3[i] << endl;
}
cout << "-----------------------------" << endl;
//5
//clear all contents of vector
input.clear();
if (input.size() == 0)
cout << "there is nothing in input vector" << endl;
return 0;
}