在 C++ 中:
std::vector<decltype(v1.front() * v2.front())> v3 { v1[0] * v2[0], v1[0] * v2[1], v1[0] * v2[2], v1[1] * v2[0], v1[1] * v2[1], v1[1] * v2[2], v1[2] * v2[0], v1[2] * v2[1], v1[2] * v2[2] };
...不过,我通常会将其格式化为多行。
作为 MCVE:
#include <iostream>
#include <vector>
using namespace std;
template <typename ELEM>
ostream& operator << (ostream &out, const vector<ELEM> &vec)
{
const char *sep = "{ ";
for (const ELEM &elem : vec) { out << sep << elem; sep = ", "; }
return out << " }";
}
int main()
{
vector<double> v1{ 1.0, 2.0, 3.0 }, v2{ 4.0, 5.0, 6.0 };
// in one line:
vector<decltype(v1.front() * v2.front())> v3 { v1[0] * v2[0], v1[0] * v2[1], v1[0] * v2[2], v1[1] * v2[0], v1[1] * v2[1], v1[1] * v2[2], v1[2] * v2[0], v1[2] * v2[1], v1[2] * v2[2] };
// output:
cout << v3 << endl;
// done
return 0;
}
输出:
{ 4, 5, 6, 8, 10, 12, 12, 15, 18 }
(在ideone上测试。)
感谢 Rory Daulton 的启发。在 C++ 中,我也可以这样做:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string operator*(const string &str1, const string &str2)
{
return str1 + str2;
}
template <typename ELEM>
ostream& operator << (ostream &out, const vector<ELEM> &vec)
{
const char *sep = "{ ";
for (const ELEM &elem : vec) { out << sep << elem; sep = ", "; }
return out << " }";
}
int main()
{
vector<string> v1{ "a", "b", "c" }, v2{ "d", "e", "f" };
// in one line:
vector<decltype(v1.front() * v2.front())> v3 { v1[0] * v2[0], v1[0] * v2[1], v1[0] * v2[2], v1[1] * v2[0], v1[1] * v2[1], v1[1] * v2[2], v1[2] * v2[0], v1[2] * v2[1], v1[2] * v2[2] };
// output:
cout << v3 << endl;
// done
return 0;
}
输出:
{ ad, ae, af, bd, be, bf, cd, ce, cf }
经过一点改进,它甚至可以用于混合类型:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string operator*(const string &arg1, int arg2)
{
string ret; for (int i = 0; i < arg2; ++i) ret += arg1;
return ret;
}
template <typename ELEM>
ostream& operator << (ostream &out, const vector<ELEM> &vec)
{
const char *sep = "{ ";
for (const ELEM &elem : vec) { out << sep << elem; sep = ", "; }
return out << " }";
}
int main()
{
vector<string> v1{ "a", "b", "c" }; vector<int> v2{ 1, 2, 3 };
// in one line:
vector<decltype(v1.front() * v2.front())> v3 { v1[0] * v2[0], v1[0] * v2[1], v1[0] * v2[2], v1[1] * v2[0], v1[1] * v2[1], v1[1] * v2[2], v1[2] * v2[0], v1[2] * v2[1], v1[2] * v2[2] };
// output:
cout << v3 << endl;
// done
return 0;
}
输出:
{ a, aa, aaa, b, bb, bbb, c, cc, ccc }