C++/Library
2021. 3. 19. 19:42
IntArray
int
자료형을 여러개 담을 수 있는 컨테이너#include <iostream> class IntArray { int* data_ = nullptr; unsigned length_ = 0; public: IntArray(unsigned length = 0) { initialize(length); } IntArray(const std::initializer_list<int>& list) { initialize(list.size()); int count = 0; for (auto& e : list) data_[count++] = e; } ~IntArray() { delete[] data_; } void initialize(unsigned length) { length_ = length; if (length_ > 0) data_ = new int[length_]; } void reset() { if (data_) { delete[] data_; data_ = nullptr; } length_ = 0; } void resize(const unsigned& length) { if (length == 0) reset(); else if (length_ < length) { int* new_data_ = new int[length]; for (unsigned i = 0; i < length_; ++i) new_data_[i] = data_[i]; delete[] data_; data_ = new_data_; } length_ = length; } void insertBefore(const int& value, const int& ix) { resize(length_ + 1); for (int i = length_ - 2; i >= ix; --i) data_[i + 1] = data_[i]; data_[ix] = value; } void remove(const int& ix) { for (int i = ix; i < length_ - 1; ++i) data_[i] = data_[i + 1]; --length_; if (length_ <= 0) reset(); } void push_back(const int& value) { insertBefore(value, length_); } friend std::ostream& operator << (std::ostream& out, const IntArray& arr) { for (unsigned i = 0; i < arr.length_; ++i) out << arr.data_[i] << ' '; return out; } }; int main() { using namespace std; IntArray my_arr{ 1, 3, 5, 7, 9 }; cout << my_arr << endl; my_arr.insertBefore(10, 1); cout << my_arr << endl; my_arr.remove(3); cout << my_arr << endl; my_arr.push_back(13); cout << my_arr << endl; } /* stdout 1 3 5 7 9 1 10 3 5 7 9 1 10 3 7 9 1 10 3 7 9 13 */
'C++ > Library' 카테고리의 다른 글
C++ std::exception (0) | 2021.03.22 |
---|---|
C++ reference_wrapper (0) | 2021.03.21 |
C++ initializer_list (0) | 2021.03.19 |
C++ chrono (0) | 2021.03.16 |
C++ assert (0) | 2021.03.12 |