C++ 표준 라이브러리 구현 살펴보기

 

컨테이너 안에 객체 배치하기

std::array는 C++11에 새로 추가된 컨테이너이다.

vector는 가변 배열, array는 고정 배열이라는 차이가 있다.

 

std::array<int, 10> a = { 0, 1, 2, .. };
std::vector<int> v = { 0, 1, 2, .. };

 

둘 다 인덱스로 컨테이너의 특정 요소에 접근할 때는 [] 연산자 대신 at 함수를 사용하는 것이 안전하다.

인덱스가 컨테이너 범위를 벗어날 때, at 함수는 out_of_range 예외를 던지는데 [] 연산자는 아무것도 하지 않기 때문에 미정의 동작이 발생할 수 있다.

 

 

알고리즘 사용하기

배열이나 벡터에 저장된 요소는 표준 라이브러리를 사용하여 정렬이나 특정 값을 찾을 수 있다.

 

◾ 정렬

/* 정렬 */
bool comparer(int a, int b)
{
    return a > b;
}

std::vector<int> vect = { 20, 43, 11, 78, 5, 96 };

std::sort(std::begin(vect), std::end(vect)); /* 기본은 오름차순 정렬 */
std::sort(std::begin(vect), std::end(vect), comparer); /* comparer를 이용해서 내림차순 정렬 */

 

3번째 인자로 비교 함수를 넘겨주면 임의의 조건으로 정렬시킬 수 있다.

 

◾ 탐색

bool TwoWheeled(const Vehicle &vehicle)
{
    return vehicle.GetNumOfWheel() == 2 ? true : false;
}

std::vector<Vehicle> vehicles;
...
auto tw = find_if(std::begin(vehicles), std::end(vehicles), TwoWheeled); // TwoWheeled : 탐색 조건
auto ntw = find_if_notstd::begin(vehicles), std::end(vehicles), TwoWheeled);

 

find_if는 탐색 조건에 부합하는 인자들을 반환하고 find_if_not은 탐색 조건에 부합하는 인자들을 제외하고 반환한다.

 

◾ 순회(루프)

void PrintOut(const Vehicle &vehicle)
{
    std::cout << vehicle.GetType() << '\n';
}

vector<Vehicle> vehicles;
...
std::for_each(std::begin(vehicles), std::end(vehicles), PrintOut);

 

루프를 돌며 컨테이너의 요소를 인자로 넘겨서 필요한 함수를 실행시킬 수도 있다.

+ Recent posts