Skip to content

Instantly share code, notes, and snippets.

@huklee
Created March 3, 2017 10:51
Show Gist options
  • Save huklee/50160508a02db4e7f446bf569db9dfdf to your computer and use it in GitHub Desktop.
Save huklee/50160508a02db4e7f446bf569db9dfdf to your computer and use it in GitHub Desktop.
[C++ STL] vector (dynamic array) example
#include <iostream>
#include <vector>
void std_vector_test(){
std::cout << "=== std::vector Test ===" << std::endl;
// 01. assignemnt
std::vector<int> v1;
v1.reserve(20); // assign the memory space of 20 * int
std::vector<int> v2(2); // assign the memory & fill 2*null(0)
// 02. stack operation
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.pop_back();
v2.push_back(10);
v2.push_back(20);
// 03. access
for(int i : v1) std::cout << i << " "; std::cout << std::endl;
// 04. insert operation
std::vector<int>::iterator li = v1.begin();
v1.insert(li + 1, 4);
v1.insert(li, v2.begin(), v2.end());
for(int i : v1) std::cout << i << " "; std::cout << std::endl;
// 05. copy from array, vector
int arr[] = {1,2,3,4};
std::vector<int> v3(arr, arr + sizeof(arr)/sizeof(int));
std::vector<int> v4(v3);
for(int i : v3) std::cout << i << " "; std::cout << std::endl;
for(int i : v4) std::cout << i << " "; std::cout << std::endl;
// 06. clear the data
v1.clear();
v2.clear();
v3.clear();
v4.clear();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment