코딩/C++
vector를 스택처럼 사용
by sonysame
2024. 3. 21.
#include <iostream>
#include <vector>
using namespace std;
void printStack(const std::vector<int>& stack) {
for (auto& e : stack) {
cout << e << " ";
}
cout << endl;
}
int main() {
std::vector<int> v{ 1,2,3 };
v.resize(10); //
for (auto& e : v)
cout << e << " "; //1 2 3 0 0 0 0 0 0 0
cout << endl;
cout << v.size() << " " << v.capacity() << endl; //10 10
v.resize(2);
for (auto& e : v)
cout << e << " "; //1 2
cout << endl;
int* ptr = v.data();
cout << ptr[2] << endl; //3
cout << v.size() << " " << v.capacity()<< endl; //2 10
///////////////////////////////////////////////////////
std::vector<int> v2{ 1,2,3 };
v2.reserve(1024);
for (auto& e : v2)
cout << e << " "; //1 2 3
cout << endl;
cout << v2.size() << " " << v2.capacity() << endl; //3 1024
///////////////////////////////////////////////////////
std::vector<int> stack;
stack.push_back(3);
printStack(stack);
stack.push_back(5);
printStack(stack);
stack.push_back(7);
printStack(stack);
stack.pop_back();
printStack(stack);
stack.pop_back();
printStack(stack);
stack.pop_back();
printStack(stack);
}