简体   繁体   English

在C ++中,如何释放向量中几个元素的内存,而对其他元素仍具有相同的索引

[英]In c++, how to free memory of few elements in a vector and still have the same indexing for other elements

I actually want to index the elements in a vector by the value it stores so that it is easy to retrieve them rather than searching for. 我实际上想通过向量中存储的值对向量中的元素进行索引,以便轻松检索而不是进行搜索。 So I do not want the vector to change its length nor the rest of the elements to change their indices. 因此,我既不希望矢量更改其长度,也不希望其他元素更改其索引。 Can this be achieved in vectors or are there any other datastructures I can use? 可以通过向量实现,还是可以使用其他数据结构?

In c++, how to free memory of few elements in a vector and still have the same indexing for other elements 在C ++中,如何释放向量中几个元素的内存,而对其他元素仍具有相同的索引

No, you can't. 不,你不能。 C++ mandates std::vector<T> to lay its elements in a contiguous memory. C ++强制std::vector<T>将其元素放置在连续的内存中。 There is no way you can free memory for elements "in-between". 您无法为“中间”的元素释放内存。

You can use std::unordered_map<int, T> . 您可以使用std::unordered_map<int, T> That way, you still have the same indexes while you can free other indexes. 这样,您仍然拥有相同的索引,而您可以释放其他索引。 However, the performance of std::unordered_map may differ from std::vector because they are completely different data structures. 但是, std::unordered_map的性能可能与std::vector不同,因为它们是完全不同的数据结构。

You should however use std::unordered_map::find(...) to obtain the index rather than it's operator [] so that you do not re-insert a default element, should the index not exist. 但是,您应该使用std::unordered_map::find(...)来获取索引,而不是其operator []这样就可以在索引不存在的情况下不重新插入默认元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM