std::list; list_type 为 (char * data, int lenght)
我有一些
std::list<char> list_type
现在我必须将列表的内容提供为(char *data,int length)。 有没有方便的方法将列表内容呈现为指针和长度?
有这样的接口吗?
先感谢您。
I have some
std::list<char> list_type
Now I have to supply contents of the list as (char *data, int length). Is there convenient way to present list contents as pointer and length? Does <vector>
has such interface?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用向量来完成此操作,因为它的数据是连续存储的:
对于列表,您必须将数据复制到数组中。 幸运的是,这也相当简单:
当然,您会留下一个动态分配的数组,您必须再次释放它。
You can do it with a vector, because its data is stored contiguously:
For list, you have to copy the data to an array. Luckily, that too is fairly easy:
Of course, you're then left with a dynamically allocated array you have to free again.
您可以使用向量来完成此操作,而不是使用列表。 向量保证是连续的内存块,因此您可以说:
You can do this with vector, not with list. A vector is guaranteed to be a contigous chunk of memory so you can say:
我不知道 std::list,但 std::vector 知道:
std::string 也可以完成这项工作,但你可能已经知道了。
I don't know about std::list, but std::vector does:
std::string can do the job too, but you probably already know it.
您无法使用列表执行此操作,因为列表将其数据保存在列表节点中。 但是,您可以使用向量来完成此操作,保证将其数据存储在连续的内存中。 您可以使用
&v[0]
或&*v.begin()
来获取指向其第一个元素的指针:请注意,向量将自动释放其第一个 元素函数返回时的内存。
还有(至少)两件事值得注意:
v[0]
。 (也不允许取消引用v.begin()
。)std::list
和std:: 之间来回转换。矢量可能是真正的性能杀手。 考虑完全切换到 std::vector 。
You cannot do this with a list, as a list saves its data in list nodes. However, you can do this with a vector, which is guaranteed to store its data in a contiguous piece of memory. You can use either
&v[0]
or&*v.begin()
to get a pointer to its first element:Note that the vector will automatically free its memory when the function returns.
There are (at least) two more noteworthy things:
v[0]
of an empty vector. (Neither are you allowed to dereferencev.begin()
.)std::list
andstd::vector
can be a real performance killer. Consider switching tostd::vector
altogether.list
是一个链表数据结构。 如果不进行转换,您就无法(理论上)做到这一点。您将能够访问 (C+ +0x Draft 23.2.6.3)C++0x 中带有
.data()
的向量
的后备存储。 目前,最好的选择是通过获取初始元素的地址将其视为数组。list
is a linked list data structure. There's no way you could do that (theoretically) without conversion.You'll be able to access (C++0x Draft 23.2.6.3) the backing store of a
vector
with.data()
in C++0x. Currently, your best bet is to treat it as an array by taking the address of the initial element.