how to implement a sparse_vector class

╄→尐↘猪︶ㄣ 提交于 2019-12-05 22:18:08

Effectively, it seems that they reinvented the wheel (so to speak).

I would personally consider 2 libraries for your need:

  • Loki, for Loki::AssocVector -> the interface of a map implemented over a vector (which is what you wish to do)
  • Boost.Iterator, for its iterator_adaptor class. Makes it very easy to implement a new container by Composition.

As a remark, I would note that you may wish to be a little more generic that values different from the T() because this impose T to be DefaultConstructible. You could provide a constructor which takes a T const&. When writing a generic container it is good to try and reduce the necessary requirements as much as possible (as long as it does not hurt performance).

Also, I would remind you that the idea of using a vector for storage is very good for a little number of values, but you might wish to change the underlying container toward a classic map or unordered_map if the number of values grows. It could be worth profiling/timing. Note that the STL offer this ability with the Container Adapters like stack, even though it could make implementation slightly harder.

Have fun.

Having indices in a separate list would make them faster to look up - as you suggest, it would use the cache more effectively, particularly if T is large.

If you want to implement your own, why not just use std::map (or std::unordered_map)? Keys would be larger but implementation time would be close to zero!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!