c++

c++ 공부(vector iterator 구현)

이야기prog 2025. 3. 6. 21:45
#include <iostream>


template<typename T>
class Iterator {

public:
	Iterator() : ptr_(nullptr) {}
	Iterator(T* ptr) : ptr_(ptr) {}


	Iterator& operator++() {
		ptr_++;
		return *this;
	}

	Iterator operator++(int) {
		Iterator tmpItr = *this;
		ptr_++;
		return tmpItr;
	}

	Iterator& operator--() {
		ptr_--;
		return *this;
	}

	Iterator operator--(int) {
		Iterator tmpItr = *this;
		ptr_--;
		return tmpItr;
	}

	Iterator operator+(const int count) {
		Iterator tmp = *this;
		tmp.ptr_ += count;
		return tmp;
	}

	Iterator operator-(const int count) {
		Iterator tmp = *this;
		tmp.ptr_ -= count;
		return tmp;
	}

	bool operator==(const Iterator& right) {
		return ptr_ == right.ptr_;
	}

	bool operator!=(const Iterator& right) {
		return !(*this == right);
	}


	T& operator*() {
		return *ptr_;
	}

public:
	T* ptr_;
};



template<typename T>
class Vector {

public:

	Vector() : data_(nullptr), size_(0), capacity_(0) {}
	~Vector() {
		if (data_)
			delete[] data_;
	}

	int size() { return size_; }
	int capacity() { return capacity_; }

	void clear() { size_ = 0; }
	void push_back(const T& val) {

		if (size_ == capacity_) {
			int newCapacity = static_cast<int>(capacity_ * 1.5);
			if (newCapacity == capacity_)
				newCapacity++;
			reserve(newCapacity);
		}
		data_[size_++] = val;
	}

	void reserve(int capacity) {


		if (capacity <= capacity_) {
			return;
		}

		capacity_ = capacity;
		T* tmpData = new T[capacity];

		for (int i = 0; i < size_; ++i) {
			tmpData[i] = data_[i];
		}

		if(data_)
			delete[] data_;

		data_ = tmpData;
	}

	T& operator[](const int i) {
		return data_[i];
	}
public:
	typedef Iterator<T> iterator;

	iterator begin() { return iterator(&data_[0]); }
	iterator end() { return  begin() + size_; }


private:
	T* data_;
	int size_;
	int capacity_;
};

int main() {

	Vector<int> v;

	v.reserve(100);

	for (int i = 0; i < 100; ++i) {

		v.push_back(i);
		std::cout << v.size() << " " << v.capacity() << std::endl;
	}

	for (int i = 0; i < v.size(); ++i) {

		std::cout << v[i] << std::endl;

	}

	std::cout << "-------------------------------------------------" << std::endl;

	for (Vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		std::cout << *it << std::endl;
	}
	
	return 0;

}

'c++' 카테고리의 다른 글

c++ 공부(algorithm)  (0) 2025.03.08
c++공부(list iterator 구현)  (0) 2025.03.07
c++ 공부  (1) 2025.03.03
c++ 공부  (0) 2025.03.01
c++ 공부  (0) 2025.03.01