简体   繁体   中英

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

No, you can't. C++ mandates std::vector<T> to lay its elements in a contiguous memory. There is no way you can free memory for elements "in-between".

You can use 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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