Asi Bside
Asi Bside

Reputation: 55

How do I implement an iterable structure?

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)
        ...;
}

Upvotes: 2

Views: 477

Answers (1)

Aaron Jones
Aaron Jones

Reputation: 131

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;
}

Upvotes: 2

Related Questions