본문 바로가기
코딩/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);

}

'코딩 > C++' 카테고리의 다른 글

Constructor  (0) 2024.05.28
Encapsulation  (0) 2024.05.28
assert  (0) 2024.03.21
함수포인터  (0) 2024.03.19
오버로딩  (0) 2024.03.19