[英]How to initialize a const int 2-dimension vector in C++
How to initialize a const int 2-dimension vector: 如何初始化const int二维向量:
Const int vector < vector < int > > v ?
v = {1 , 1 ; 1, 0} ?
it does not work . 这是行不通的 。
You can do this ( only in C++11 ): 你可以这样做( 仅在C ++ 11中 ):
const vector<vector<int>> v{{1,2,3},{4,5,6}};
Also note that you don't need to write > >
. 另请注意,您无需编写> >
。 As this issue has been fixed in C++11, >>
would work. 由于此问题已在C ++ 11中得到修复,因此>>
可行。 It wouldn't be interpreted as right-shift operator (as was the case with C++03). 它不会被解释为右移运算符(与C ++ 03的情况一样)。
If your compiler supports the initialisation-list feature (is that what it's called?) of C++11, you can do this: 如果您的编译器支持C ++ 11的初始化列表功能(就是它的名称?),您可以这样做:
const vector<vector<int>> v {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Note that you won't be able to add any elements to the first dimension (but you can add elements to the second), eg 请注意,您将无法向第一维添加任何元素(但您可以向第二维添加元素),例如
v.push_back(vector<int> { 8, 9, 10 }); // BAD
v[0].push_back(4); // OK
If you wanted the second dimension to be non-modifiable, you'd do 如果你想让第二个维度不可修改,你就可以做到
vector<const vector<int>> {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Then 然后
v.push_back(const vector<int> { 8, 9, 10 }); // OK
v[0].push_back(4); // BAD
OR if you want the elements themselves to be const
, you would do 或者如果你想要元素本身是const
,你会这样做
vector<vector<const int>> {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Then 然后
v.push_back(vector<const int> { 8, 9, 10 }); // OK
v[0].push_back(4); // OK
v[0][0] = 2; // BAD
You probably want to modify it at runtime, so it's probably good to remove the const
altogether. 您可能希望在运行时修改它,因此最好完全删除const
。
using namespace std;
int main(void){
const vector< vector<int> > v(10, vector<int>(10,1));
return 0;
}
Initialises a 10x10 array to 1 将10x10数组初始化为1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.