提问人: 提问时间:7/17/2023 更新时间:7/18/2023 访问量:141
创建固定大小的类型向量列表
creating a list of type vectors of fixed size
问:
我想要一个 vector size=3 的 vector 类型列表
我试过写作
typedef vector<int> vec; list<vec(3)> q;
但它给了我这个错误
sol.cpp:22:12: error: temporary of non-literal type ‘vec’ {aka ‘std::vector<int>’} in a constant expression
22 | list<vec(3)> q;
| ^~~~~~
In file included from /usr/include/c++/11/vector:67,
from /usr/include/c++/11/functional:62,
from /usr/include/c++/11/pstl/glue_algorithm_defs.h:13,
from /usr/include/c++/11/algorithm:74,
from /usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h:65,
from sol.cpp:3:
/usr/include/c++/11/bits/stl_vector.h:389:11: note: ‘std::vector<int>’ is not literal because:
389 | class vector : protected _Vector_base<_Tp, _Alloc>
| ^~~~~~
答:
2赞
PaulMcKenzie
7/17/2023
#1
没有固定大小的东西。std::vector
如果必须将条目数限制为 3,请使用:std::array<int, 3>
#include <array>
#include <list>
#include <iostream>
using Array3 = std::array<int, 3>;
using ListArray3 = std::list<Array3>;
int main()
{
ListArray3 l3 = {{1,2,3},{4,5,6}};
std::cout << "The number of arrays in the list are: " << l3.size() << "\n";
for (auto& a : l3)
{
for (auto i : a)
std::cout << i << " ";
std::cout << "\n";
}
}
输出:
The number of arrays in the list are: 2
1 2 3
4 5 6
评论
0赞
doug
7/18/2023
为了回答 OP 的问题,有一种方法可以制作固定大小的 std::vector。 例如。它的大小是固定的。但是,您不能将它们放在列表或向量等中,因为不允许使用 allocator<const T>。哦,元素可以修改:也就是说,是的,只需使用,并且与常量向量不同,它们可以放在容器中。const std::vector<int> v(3);
const_cast<int&>(v[0]) = 42;
std::array
1赞
micaiah
7/18/2023
#2
如果你真的想要一个大小为 3 的列表,你只需要创建一个列表,然后构造每个大小为 3 的向量。例如,以下行创建一个包含 4 个向量的列表,每个向量的大小为 3:std::vector<int>
std::vector<int>
std::list<std::vector<int>> ls(4, std::vector<int>(3));
但是,没有什么可以阻止您更改这些向量的大小或向列表中添加更多大小不是 3 的向量。如果要编译时保证此列表中的每个对象都应具有大小 3,则应使用 而不是 。例如,以下行创建一个大小为 3 的数组的空列表:std::array
std::vector
std::list<std::array<int, 3>> ls;
上一个:小数据的链表
评论
std::array<int, 3>
std::tuple
std::list
需要将类型作为其第一个模板参数。 不是一个类型。它是一个对象。vec(3)