Is there a C ++ equivalent for the Java Collection interface for STL container classes?

I would like to pass an arbitrary container as an argument to a function and iterate over it (without erasing and clicking elements). Unfortunately, there seems to be no standard way to do this.

The first solution that comes to my mind is an interface (let it be called CollectionInterface) implemented by classes that will wrap STL containers. therefore, the function declaration will look like this:

f(const CollectionInterface * collection);

Or I was thinking of a method template, which has the advantage that it retains the binding at compile time:

template <class CONTAINER> void f(const CONTAINER & collection);

How do you think is better?

+3
source share
3

ForwardIterator? InputIterator ( OutputIterator), ( ).

( Java) , ++. ( ) <algorithm>. , search ForwardIterator. [first1, last1] , [first2, last2). , ForwardIterator.

+7

, , , . - begin() end(), rbegin() rend() . , , ; , .

template<typename Container> void Function(const Container& c) {
    for(typename Container::const_iterator i = c.begin(), end = c.end(); i != end; ++i)
       //do something
}

, , begin() end(), , . .

+4

( ).

Skip iterators. Here is an example of implementation and use:

template <typename Iter>
void function(Iter begin, Iter end)
{
    for (Iter it = begin; it != end; ++it)
    {
        std::cout << *it << std::endl;
    }
}

int main()
{
    std::string array[] = {"hello", "array", "world"};
    function(array, array + 3);

    std::vector<std::string> vec = {"hello", "vector", "world"};
    function(vec.begin(), vec.end());
}

Please note that in many cases you really do not need to write this function, but you can build it using the library tools, and then simply apply to it std::for_each. Or better yet, use an existing algorithm, such as std::accumulateor std::find_if.

+4
source

Source: https://habr.com/ru/post/1751107/


All Articles