0

I'm using C++. I would like to design a class that I can walk through similarly to std::vector, i.e.:

class Something
{
void AddABunchOfObjects() {...}

//
// Is it possible to do the below, in some form or syntax?
//
operator for (?????) {return GetObjectAtIterator();}
};

Somethign my_custom_object_container;
my_custom_object_container.AddABunchOfObjects();
for (auto &objectname : my_custom_object_container)

I don't want to use std::vector because there's a little extra work I want done with each fetch (and why can't we override/inherit std's classes anyway? Whence object-oriented? /rant)

I can't seem to find this info online, if it's possible (or I'm not using the right keywords). Is there some sort of operator override or equivalent that can be used to make a class able to iterate?

KiraHoneybee
  • 495
  • 3
  • 12
  • 1
    You need to add `begin()` and `end()` member functions that return iterators. – Ted Lyngmo Jun 26 '22 at 18:49
  • 1
    and probably `cbegin` and `cend` so you can operator on constant instances. – user4581301 Jun 26 '22 at 18:50
  • Hi @TedLyngmo, is there any info online? Does that for loop just expand like a define when compiled, or will I need to inherit the container class from something? – KiraHoneybee Jun 26 '22 at 18:50
  • It just expands into an iterator loop from (c)begin to (c)end – Goswin von Brederlow Jun 26 '22 at 18:50
  • 1
    [See the explanation here for details on what's really going on.](https://en.cppreference.com/w/cpp/language/range-for) – user4581301 Jun 26 '22 at 18:51
  • 2
    There's this old answer:[How to implement an STL-style iterator and avoid common pitfalls?](https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls) that exmplains some. It's perhaps a bit outdated though. – Ted Lyngmo Jun 26 '22 at 18:51
  • 1
    @KiraHoneybee *I don't want to use std::vector because there's a little extra work I want done with each fetch* -- For `std::vector`, did you try `std::for_each` with a custom lambda? And what is this "extra work"? I ask, because most, if not a vast majority of C++ programmers don't need to do what you're attempting to do, and instead use the available STL algorithm functions. – PaulMcKenzie Jun 26 '22 at 18:54
  • Thanks everyone for the help! I was able to implement it. @TedLyngmo if you want to post as an answer I'll accept it. – KiraHoneybee Jun 26 '22 at 19:24
  • @KiraHoneybee Thanks, but I can't since the question has been closed as a duplicate. – Ted Lyngmo Jun 26 '22 at 19:37

0 Answers0