前提・実現したいこと
Vectorには、様々な方法で初期化できるようコントラスタが用意されています。
その中で、std::vector<int> test = { 1, 2, 3, 4, 5}; という初期化の方法があると思うのですが、自分でこのようなコントラスタを用意しようとしても、どのような記述をすれば良いのか皆目見当もつきません・・・
ご存知の方、いらっしゃいますか?
該当のソースコード
C++(Visual Studio 2017)
.#include <iostream>
.#include <vector>
// 静的配列のクラス(特殊化は考えない)
template <typename T> class MyAry {
private:
// メンバ変数
T *ary;
const size_t ary_size;
private:
// 使用されたくないコントラスタ
MyAry(void) {} // 引数なし
public:
// コントラスタ
// 配列と、要素数が引数
MyAry(const size_t i_ary_size, const T i_ary[])
: ary_size(i_ary_size)
{
ary = new T[ary_size];
for (int i = 0; i < (int)ary_size; i++)
ary[i] = i_ary[i];
}
// {1, 2, 3, 4, 5}みたいなやつ
// MyAry()
// : ary_size( )
// {
// ary = new T[ary_size];
//
// }
//// デストラクタ
~MyAry() {
delete[] ary;
}
public:
// 演算子のオーバーロード
T& operator [](int ary_num) {
if (ary_num < 0 || (size_t)ary_num >= ary_size) {
cerr << "ary choice miss" << endl;
return ary[0];
}
else return ary[ary_num];
}
public:
// 公開関数
size_t arySize() const { return ary_size; } // 要素数を渡す
};
auto main() -> int {
std::vector<int> test = { 1, 2, 3, 4, 5 }; // <-この実装方法を知りたい
int temp[4] = { 6, 7, 8, 9 }; MyAry<int> mytest(4, temp); //MyAry<int> mytest2 = { -1, -2, -3, -4 }; std::cout << test[2] << std::endl; std::cout << mytest[2] << std::endl; //std::cout << mytest2[2] << std::endl; return 0;
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/13 12:37
2018/12/13 19:55