무민은귀여워

vector 구현 본문

IT/기타

vector 구현

moomini 2021. 5. 17. 23:34
반응형
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class Mylistiterator
{
public:
Mylistiterator(T* _data)
{
data = _data;
}
Mylistiterator operator++()
{
return ++data;
}
Mylistiterator operator--()
{
return --data;
}
T& operator*()
{
return *data;
}
T* operator->()
{
return data;
}
bool operator!=(const Mylistiterator<T>& InItr)
{
return data != InItr.data;
}
bool operator==(const Mylistiterator<T>& InItr)
{
return data == InItr.data;
}
Mylistiterator& operator=(const Mylistiterator<T>& InItr)
{
data = InItr.data;
return *this;
}
Mylistiterator operator++(int)
{
Mylistiterator temp = *this;
++* this;
return temp;
}
T* data;
};
template<typename T>
class MyVector
{
public:
MyVector() : capecitySize(3), top(-1), data(nullptr)
{
}
void push_back(const T& in)
{
if (data == nullptr)
{
data = new T[capecitySize];
}
if (top + 1 >= capecitySize)
{
T* Temp = data;
capecitySize *= 2;
data = new T[capecitySize];
memcpy(data, Temp, sizeof(T) * (top + 1));
delete[] Temp;
}
data[++top] = in;
}
T at(int idx)
{
if (idx <= top)
return data[idx];
else
return NULL; // 원소가 없을 때 일단 NULL을 반환
}
void push_back(T&& in)
{
if (data == nullptr)
{
data = new T[capecitySize];
}
if (top + 1 >= capecitySize)
{
T* Temp = data;
capecitySize *= 2;
data = new T[capecitySize];
memcpy(data, Temp, sizeof(T) * (top + 1));
delete[] Temp;
}
data[++top] = in;
}
T pop()
{
int temp = data[top];
top--;
return temp;
}
int size()
{
return top + 1;
}
int front()
{
return data[0];
}
Mylistiterator<T> begin()
{
return Mylistiterator<T>(data);
}
Mylistiterator<T> end()
{
return Mylistiterator<T>(data + top + 1);
}
int capecitySize;
int top;
T* data;
};
int main()
{
MyVector<int> ve;
ve.push_back(111);
ve.push_back(222);
ve.push_back(333);
ve.push_back(444);
ve.push_back(555);
cout << "top: " << ve.top << endl;
cout << "size : " << ve.size() << endl;
cout << ve.data[0] << " | " << ve.data[1] << " | " << ve.data[2] << " | " << ve.data[3] << " | " << endl;
cout << ve.at(0) << " | " << ve.at(1) << " | " << ve.at(2) << " | " << ve.at(3) << " | " << endl;
cout << "전체 출력 : " << endl;
for (auto itr = ve.begin(); itr != ve.end(); ++itr)
{
cout << *itr << endl;
}
cout << "pop 세번 : " << endl;
cout << ve.pop() << endl;
cout << ve.pop() << endl;
cout << ve.pop() << endl;
cout << "top: " << ve.top << endl;
cout << "ve.at(3) " << ve.at(3) << endl;
cout << "==============================" << endl;
cout << "전체 출력 : " << endl;
for (auto itr = ve.begin(); itr != ve.end(); ++itr)
{
cout << *itr << endl;
}
cout << " front : " << ve.front() << endl;
return 0;
}
반응형

'IT > 기타' 카테고리의 다른 글

stack 구현  (0) 2021.05.17
list 구현  (0) 2021.05.17
xcode 11에서 cocos2d-x v3 빌드 실패 시 해결 방법  (0) 2020.02.25
프로세스와 스레드의 차이  (0) 2019.12.14
memo) LearnOpenGL 예제 번역 블로그  (0) 2019.12.04
Comments