Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over collections generically in C++?

Simply put, if I have a set and vector how do I create a generic method that can handle both as params.

All I want to do, is iterate over either types of collections. Sounds like it should be trivial but I'm missing something.

void printMeSomeStrings(somebaseclass<string> strings) {
  for (auto& str : strings) {
    cout << str << endl;
  }
}

In C#, I would pass IEnumerable or something like that. Then I could iterate over the collection.

Any general reading explaining the answer would be appreciated.

like image 547
deliberative assembly Avatar asked May 14 '13 15:05

deliberative assembly


People also ask

How do I iterate through collections?

There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write.

Which loop we must use in order to iterate over a collection?

First use a for-each loop when it is appropriate: iterating over the whole collection and only needing the elements (not their index).

Can we use for loop in collection?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

How do you iterate through a set of elements?

Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.


1 Answers

You could use templates. For instance:

#include <iostream>

template<typename C>
void foo(C const& c)
{
    std::cout << "{ ";
    for (auto const& x : c)
    {
        std::cout << x << " ";
    }
    std::cout << "}";
}

And here is how you would use it:

#include <set>
#include <vector>

int main()
{
    std::vector<int> v = {1, 2, 3};
    foo(v);

    std::cout << std::endl;

    std::set<std::string> s = {"Hello,", "Generic", "World!"};
    foo(s);
}

Live example.

like image 101
Andy Prowl Avatar answered Nov 14 '22 06:11

Andy Prowl