2

I want to write a structure through which I can loop. For this I added two methods begin and end which would return begin, end values of an already existing vector. What return type should I specify, and will these two methods be enough to make MATCH structure work in my context? Here's what I've got so far:

typedef std::pair<std::string, std::string> combo;
struct MATCH {
    std::vector<combo> matches;
    ? begin() { return matches.begin(); }
    ? end() { return matches.end(); }
};

int main() {
    MATCH m = { ... };
    for (const combo& i : m)
        ...;
}
Asi Bside
  • 45
  • 3
  • Does this answer your question? [How to make my custom type to work with "range-based for loops"?](https://stackoverflow.com/questions/8164567/how-to-make-my-custom-type-to-work-with-range-based-for-loops) – Passerby Jan 07 '22 at 23:52
  • I recommend using a different container than a `struct`; one that is iterable. Otherwise, I recommend implementing iterators. Based on the value of an iteration, you can return the member; however, in order for this to work, you'll need to have all the members the same types. – Thomas Matthews Jan 07 '22 at 23:53

1 Answers1

2

I think the type you're looking for is std::vector<combo>::iterator.

Example:

typedef std::pair<std::string, std::string> combo;
struct MATCH {
    std::vector<combo> matches;
    std::vector<combo>::iterator begin() { return matches.begin(); }
    std::vector<combo>::iterator end() { return matches.end(); }
};


int main()
{
    MATCH m = { { {"something", "something"} } };
    for (const combo& i : m)
        cout << i.first << " " << i.second << std::endl;
   
   return 0;
}
Aaron Jones
  • 131
  • 3
  • 1
    Good place to use the keyword `auto` – Martin York Jan 08 '22 at 01:05
  • 2
    Though you might also want `std::vector::const_iterator begin() const { return matches.begin(); }` and likewise for `end()`. Or in some cases, maybe only the `const` versions. – aschepler Jan 08 '22 at 01:34