공부하기 싫을 때 쓰는 블로그
[data structure with c++] std vector 1. pointers 본문
여름방학은 어떤 공부를 해도 어수선한 느낌을 지울 수 없다.
짜놓은 시간표대로 정해진 시간에 정해진 일과가 반복될때
느껴지는 생활의 리듬감을 상실해 버린게 떄로는 아쉽기도 하다 (개강 빨리ㅎㅎ)
이번주부터 몇번에 걸쳐 c++ 로 기초 자료구조와 알고리즘을 공부하려고 한다.
(동시에 회로이론도 복습하고 논리설계도 예습해야 되서 많이는 못하고)
그 첫 단추로 c++의 가장 기본적인 data structure인 vector를 직접 구현한다.
standard library의 일부이지만, 그 작동을 이해하기 위해서 순전히 기초적인 툴들만 가지고 구현해 보기로 한다.
물론 이게 내 첫 cpp 프로젝트인 만큼,
직접 하지는 않고 Stroutstrup 교재의 17-19장에 outline된 방법을 고스란히 따라하기로 한다.
관심있으면 찾아보자(책이 좀... 사람 정신없게 만드는 방향으로 말이 많긴 해서 호불호가 갈릴 수는 있으니 주의)
1. Pointers
three operators:
- get the address of : &
- read the object pointed to by a pointer : * (the dereference)
- read the nth object pointed by p, n=>1 : [n-1] (the subscript) (i.e. for first object, [0])
int x = 17;
int* pi = &x // returns the address of x, something like 00DAFA34
pi[0] = 18; //sets the integer referenced by pi to 18.
double* p = new double[4]; //allocate 4 doubles from heap.
*p = 7.7;
new가 heap 이라는 비어있는 메모리 공간에서 double을 담을 수 있는 크기의 메모리 4개를 할당(allocate)해 준다.
만약 new 없이 그냥 uninitialized 된 포인터를 바로 쓴다면?
int* pi;
*pi = 1;
어.. uninitialized 된 포인터는 어디를 가리키고 있을지 모른다. 위험하다!
unitialized된 상태로 두기보단 차라리 nullptr로 정해두자.
double* p0 = nullptr;
if(p0) { ... } // check if nullptr.
Q) what is the value of p[0] and p[1]?
cout << "p[0]==" << *p << "; p[1]==" << p[1];
A)
p[0]==7.7; p[1]==-6.27744e+66(some random number)
난 0.0으로 채워줄 줄 알았다. 안해주네..
initialization 을 하려면 아래처럼 해준다.
특히, custom type 에 default constructor가 정의된 경우 그 constructor로 initialize 된다.
double* p = new double{5.5}; //initialized to 5.5
double* p1 = new double[] {0,1,2,3,4};
double* py = new Y{13}; //Y is a custom type with a constructor.
double* py = new Y[5]; //if Y has a default constructor, this will be default-initialized!
//note when initialization is provided the number of elements can be left out.
쓴 메모리는 다시 반납해주자.
int* p = new int{5};
delete p;
이것보다 복잡하게는..
double* calc(int res_size, int max)
{
double* p = new double[max];
double* res = new double[res_size];
// done with using p and filling out res.
delete[] p; //free
return res;
}
double* r = calc(100,1000);
delete[] r; //don't need anymore, delete.
이 함수는 double을 가르키는 pointer를 return 한다.
자 그럼 이제 pointer를 대강 다뤘으니,
vector를 implement 하러 가보자.