【发布时间】:2018-09-30 14:39:02
【问题描述】:
在 C++11 中,{} 优于 () 用于变量初始化。但是,我注意到 {} 无法正确初始化向量的向量。
鉴于以下代码,vector<vector<int>> mat2(rows, vector<int>(cols, 2)) 和 vector<vector<int>> mat4{rows, vector<int>(cols, 4)} 可以按预期工作,但 vector<vector<int>> mat1{rows, vector<int>{cols, 1}} 和 vector<vector<int>> mat3(rows, vector<int>{cols, 3}) 不会。谁能解释一下为什么?
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
string parse_matrix(const vector<vector<int>>& mat)
{
stringstream ss;
for (const auto& row : mat) {
for (const auto& num : row)
ss << std::setw(3) << num;
ss << endl;
}
return ss.str();
}
int main()
{
const int rows = 5;
const int cols = 4;
vector<vector<int>> mat1{rows, vector<int>{cols, 1}};
vector<vector<int>> mat2(rows, vector<int>(cols, 2));
vector<vector<int>> mat3(rows, vector<int>{cols, 3});
vector<vector<int>> mat4{rows, vector<int>(cols, 4)};
cout << "mat1:\n" << parse_matrix(mat1);
cout << "mat2:\n" << parse_matrix(mat2);
cout << "mat3:\n" << parse_matrix(mat3);
cout << "mat4:\n" << parse_matrix(mat4);
}
输出:
$ g++ -Wall -std=c++14 -o vector_test2 vector_test2.cc
$ ./vector_test2
mat1:
4 1
4 1
4 1
4 1
4 1
mat2:
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
mat3:
4 3
4 3
4 3
4 3
4 3
mat4:
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4
【问题讨论】:
-
不确定这是否是一个完整的答案,但对于每个矩阵,您都使用不同的括号和大括号组合。建议您在尝试调试之前标准化您的调用。
-
@Immersive 如果你真的阅读了这个问题,你就会意识到括号/大括号的变化是整个探究的重点。
-
公平的警察。我略读了一下,读作“为什么输出不一致”。