0

I have a class implementing data structure (some kind of hash map) with 3 vectors.

std::vector<uint64_t> keys;  // storage of keys to values (actually hash values)
std::vector<int> values; // storage for values (some integer)
std::vector<bool> allocated; // vector of allocated elements

Each of the vectors have the same size (for example 8 elements)

It would look like this

keys:      32233 52263 0     22224 0    87222  65432  0
values:    234   44    0     43    0    78     98     0
allocated: 1     1     0     1     0    1      1      0

I would like to implement a custom iterator that can iterate over the allocated vector and being able to return the corresponding value of the values vector and the key of the keys vector. The empty spots (marked as 0 in the allocated vector) should be ignored as these spots are considered as free spots. I thought I might be able to return a pair type of each iterated allocated spot, like std::pair< key, value > or such so I would have they key as it->first and the value as it->second.

I really have no idea how to get a start on implementing this. Is this possible at all? Would be great if someone can give me small sample code. Maybe this is even more simple then I think.

Thanks in advance for your help!

Andreas W. Wylach
  • 723
  • 2
  • 10
  • 31
  • why don't you use a `std::vector< std::pair >`? Or even better, a `std::unordered_map`? – TemplateRex Feb 06 '13 at 14:12
  • @rhalbersma: I know it would be a better way like this. But it is an existing class I would like to modify. I will change that later when I refactor it. – Andreas W. Wylach Feb 06 '13 at 14:14
  • by writing complicated algorithms on sub-optimal datastructures, you are creating [technical debt](http://www.codinghorror.com/blog/2009/02/paying-down-your-technical-debt.html) that will be much more expensive to pay back down the road – TemplateRex Feb 06 '13 at 14:17
  • @MadKeithV: Yes I just recognized that, I didn't find that answer earlier. It is a good hint! – Andreas W. Wylach Feb 06 '13 at 14:20
  • @rhalbersma: This is essentially the choice between "struct of arrays" and "array of structs", both of which have pros and cons... – Oliver Charlesworth Feb 06 '13 at 14:20
  • @OliCharlesworth point taken, but since the OP mentioned it was "some kind of hash map", why not start from there immediately? zip iterators and all that are nice, but if you know up front that the two ranges have a `Key, Value` relationship, why go down that road? – TemplateRex Feb 06 '13 at 14:25
  • @rhalbersma: Because it is existing code and I would like to try something first. As I confirmed you already before, it is surely better to choose an unordered_map or some other existing good implementation. Also I take that as an exercise implementing this iterator. – Andreas W. Wylach Feb 06 '13 at 14:33

0 Answers0