C ++向量与动态项大小 [英] C++ vector with dynamic item size

查看:147
本文介绍了C ++向量与动态项大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ STL向量有很多不错的属性,但只有在每个项目的大小在运行时已知时才起作用。

the C++ STL vector has a lot of decent properties, but only works when the size of each item is known at run-time.

我想要一个在运行时具有动态项大小的向量类。

I would like to have a vector class that features dynamic item size at run-time.

背景:我的项目由一个整数和双精度序列组成;一个只在运行时才知道的序列。

Background: My items consist of a sequence of integers and doubles; a sequence which is only known at run-time. It would suffice to have the vector be given the size of each item at run-time.

我知道可能的解决方法,但这些往往不能反映基本的想法的算法,这总是一个关于维护的坏事。是否有提供这样方便和工作效率的工作,如同预期一样?

I am aware of possible workarounds, but these tend not to reflect the underlying idea of the algorithm, which is always a bad thing with regards to maintainance. Are there classes which provide such a convenience and work as efficient as one might expect?

编辑:

不是关于在整个数组中变化的项目大小。它与无关。 它在运行时决定数组中的项目有多大;

This is not about item sizes varying throughout the array. It has nothing to do with that. It is at run-time deciding how large the items in the array are; i.e. a (very) weak form of dynamic typing, in contrast to static typing as used with templates.

因此,对象的初始化应该看起来像这样:

Hence the initialization of the object should look like that:

DynamicVector V( lengthofvector, sizeofelement );

应用程序是简单的网格。对象$ V $包含固定大小或类型的项目,每个由用于拓扑信息的整数组成,并且对于一些几何信息加倍。

An application are simplicial meshes. The object $V$ contains items of fixed size or "type", each consisting of integers for the topological information and doubles for some geometric information. There might even come booleans into play, but this is irrelevant so far.

推荐答案

问题是,如果你没有

只要将所有项目存储为<$,就可以将所有项目存储在向量中。 c $ c> double ?

What about just storing ALL the items as double? This drastically simplifies things.

或者您可以考虑 boost :: variant

编辑:但是真的可以解释一下为什么要在同一个序列中存储两个不同的类型?这有时可能表明底层设计需要进一步思考。

But really can you explain further why you want to store two different types in the same sequence? That can sometimes indicate that the underlying design needs further thought.

这篇关于C ++向量与动态项大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆