C++ templateでstd::vector もどきを実装してみる。
#include <iostream>
template <class T> class List {
public:
List();
List(int size);
~List();
T& operator[](int index);
private:
T* data;
};
template <class T> List<T>::List(int size) {
data = new T[size];
return;
}
template <class T> List<T>::~List() {
delete[] data;
return;
}
template <class T> T& List<T>::operator[](int index) {
return data[index];
}
int main()
{
List<int> list(4);
list[0] = -1;
std::cout << "Hello World!" << list[0] << std::endl;
return 0;
}ListVector構造に添字(インデックス)でアクセスするのが目的。
動かしてみる。
$ g++ -std=c++11 list.cpp $ ./a.out Hello World!-1
動いた!
参考:
9.8 — Overloading the subscript operator | Learn C++
2016/11/13 追記
コメントで指摘いただきましたが、紹介したコードがデータ構造上List(std::list)よりVector(std::vector)に近い構造のため、ListをVectorに修正させていただきます。