C++/C to C++
[C to C++] C++ 스타일에 맞춰 vector 작성하기
nodeal
2019. 1. 28. 19:39
반응형
추가되는 사항
- C++ 구조체에는 멤버 함수를 추가할 수 있다.
- C++ 구조체의 멤버 함수가 멤버 변수를 수정하지 않을 때에는 const 기호를 추가할 수 있다.
struct Object { int v; int foo() const { return v; } int bar() { return v; } }; const Object o; o.foo(); // OK o.bar(); // Error: Non-const member function
- C++에서 raw pointer를 동적 할당, 해제할 때는 new-delete을 사용한다.
> malloc, free는 더 이상 사용되지 않는다. - constexpr을 이용해서 상수를 정의한다.
> 더 이상 #define을 이용해서 상수를 정의하지 않는다. - C++에서 raw pointer를 복사할 때는 std::copy (<algorithm>에 정의되어 있음)를 사용한다.
> memcpy는 더 이상 사용되지 않는다. - C++에서 논리 자료형을 반환할 때는 bool을 사용한다.
> 더 이상 비표준 논리 자료형이나 정수 자료형을 사용하지 않는다. - 변수 선언과 함께 초기화되는 경우 auto를 사용한다.
> 초기화되는 타입으로 지정이 가능한 경우 명시적으로 타입을 지정하지 않는다. - 표준 입출력은 <iostream>에 정의되어있는 std::cout, std::cin으로 한다. 개행문자는 std::endl이다.
> printf("fmt\n", ...) 꼴의 출력은 사용하지 않는다.
목표
- C style로 작성된 vector의 helper함수를 C++ struct의 멤버 함수로 추가한다.
- C++ 컴파일러에서 작동할 수 있도록 작성한다.
디자인
- 구조체 vector에 다음의 멤버 함수가 추가된다. (설명 생략, 이전 내용 참조)
- int ensure_capacity(int to_add)
- void increase_capacity()
- void initialize()
- void finalize()
- void add(int element)
- int get(int index)
- int set(int index, int element)
- int remove(int index)
- void print()
구현
#include <iostream> #include <algorithm> constexpr int INITIAL_SIZE = 10; struct vector { int* data; int capacity; int length; bool ensure_capacity(int to_add) const { return length + to_add < capacity; } void increase_capacity() { auto tmp = data; data = new int[capacity * 2]; std::copy(tmp, tmp + length, data); delete[] tmp; capacity *= 2; } void initialize() { data = new int[INITIAL_SIZE]; capacity = INITIAL_SIZE; length = 0; } void finalize() { delete[] data; } void add(int element) { if (!ensure_capacity(1)) increase_capacity(); *(data + length++) = element; } int get(int index) const { return *(data + index); } int set(int index, int element) { auto tmp = *(data + index); *(data + index) = element; return tmp; } int remove(int index) { auto tmp = *(data + index); auto tail_length = length - index - 1; auto tail = new int[tail_length]; std::copy(data + index + 1, data + length, tail); std::copy(tail, tail + tail_length, data + index); delete[] tail; length--; return tmp; } void print() const { std::cout << '{'; for (int i = 0; i < length; i++) std::cout << *(data + i) << ((i < length - 1) ? ", " : ""); std::cout << '}' << std::endl; } };
반응형