-4
配列の長さを出力するクラスArray1のヘッダに以下の関数を定義しています。配列の配列のための<<演算子のオーバーライド
friend std::ostream& operator<<(std::ostream &out,Array1<T> x)
{
out<<x.length();
}
しかし、どのように私は
Array1<Array1<double>> myarray;
配列の長さを出力するクラスArray1のヘッダに以下の関数を定義しています。配列の配列のための<<演算子のオーバーライド
friend std::ostream& operator<<(std::ostream &out,Array1<T> x)
{
out<<x.length();
}
しかし、どのように私は
Array1<Array1<double>> myarray;
のようなオブジェクトの長さの合計を印刷する< <演算子を使用することができ、私はそれをこのようにします:
`>` `での欠落#include <vector>
#include <iostream>
// I don't know what your Array1 looks like but for this demo
// deriving from std::vector seems reasonable
template<class T> struct Array1 : std::vector<T>
{
};
// general case of computing a length of an array
template<class T> std::size_t totalArrayLength(Array1<T> const& a)
{
return a.size();
}
// specific case of an array of arrays
template<class T> std::size_t totalArrayLength(Array1<Array1<T>> const& a)
{
auto total = std::size_t(0);
for (auto const& i : a) {
total += totalArrayLength(i);
}
return total;
}
// defer to the totalArrayLength function overloads for length
// computation
template<class T>
std::ostream& operator<<(std::ostream& os, const Array1<T>& a)
{
return os << totalArrayLength(a);
}
int main()
{
Array1<Array1<int>> a;
a.push_back({});
a.push_back({});
a[0].push_back(1);
a[0].push_back(2);
a[0].push_back(3);
a[1].push_back(4);
a[1].push_back(5);
a[1].push_back(6);
std::cout << a << std::endl;
// works with any number of dimensions
Array1<Array1<Array1<int>>> aaa;
aaa.push_back(a);
aaa.push_back(a);
std::cout << aaa << std::endl;
}
(std :: ostream&out、Array1 < Array1 x) ' –
Raindrop7
ありがとう、私はそれを編集しました。 – user8055946
まだコンパイルされません。 'Array *'は(暗黙的な暗黙の変換が定義されていない限り) 'x'の型と一致しません。あなたは[mcve]を提供できますか? –
BartoszKP