std::list 固定大小

发布于 2024-09-26 15:41:06 字数 45 浏览 0 评论 0原文

如何创建具有固定元素计数的 std::list

How can I create std::list with a fixed element count?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

单挑你×的.吻 2024-10-03 15:41:06

如果您只想要一个固定大小的容器,也许您正在寻找 std: :tr1::数组。 (或者只是 C++0x 的 std::array 。)

如果您不插入或删除元素,我认为使用 std::list 没有任何优势code> 而不是 std::arraystd::vector

If you just want a fixed size container, maybe you are looking for std::tr1::array. (Or just std::array for C++0x.)

If you don't insert or remove elements I don't think there is any advantage in using std::list instead of std::array or std::vector.

内心荒芜 2024-10-03 15:41:06
#include <list>

// list with 5 elements, using default constructor
const size_t fixedListSize(5);
std::list<int> mylist(fixedListSize);  

如果您希望它始终具有恰好 5 个元素,则必须将其包装在外观类中以防止插入和删除。

如果这确实是您想要的,那么您最好使用不同的容器而不是 list,因为正如其他响应中所述,您将隐藏 list 最有利的功能代码>.

#include <list>

// list with 5 elements, using default constructor
const size_t fixedListSize(5);
std::list<int> mylist(fixedListSize);  

If you want it to always have exactly 5 elements you'd have to wrap it in a facade class to prevent insertion and erasure.

If that is indeed what you want, you'd be better off using a different container instead of list, since as noted in other responses you would be hiding the most advantageous features of list.

属性 2024-10-03 15:41:06

您应该使用 std::list 构造函数。

explicit list (size_type n, const T& value = T(), const Allocator& = Allocator());

只需在创建时指定元素的确切数量即可。

std::list<int> someList(20);

您也可以为每个元素指定初始值。

std::list<int> someList(20, int(42));

std::list::resize 也是正确的解决方案。

You should use std::list constructor.

explicit list (size_type n, const T& value = T(), const Allocator& = Allocator());

Just specify at time of creation exact count of elements.

std::list<int> someList(20);

You could specify initial value for each element too.

std::list<int> someList(20, int(42));

std::list::resize is the right solution too.

溺深海 2024-10-03 15:41:06

我不得不问你,为什么你希望它有固定数量的元素以及为什么使用列表?

用户可能正在实施具有有限数量的元素和 LRU 删除策略的缓存。在这种情况下,列表是一个很好的集合。每当访问一个元素时,您都会将该元素拼接到列表的前面。如果您需要插入一个新的 elemenet(因此列表已满),您可以从列表的后面弹出。

您还可以维护某种元素查找,但 std::list 是处理 LRU 的最佳类。

I would have to ask you, why you want it to have a fixed number of elements and why use a list?

It could be that the user is implementing a cache with a limited number of elements and an LRU policy of removal. In that case a list is a good collection to use. Any time an element is accessed, you splice that element to the front of the list. If you need to insert a new elemenet (so the list gets full) you pop off the back of the list.

You can also maintain some kind of lookup for the elements but std::list is the best class to handle LRU.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文