the STL algorithms use iterators, not containers, why?

Help me, please
What if you want to process only part of values in container? In reverse order? Every second one? Where would output go? To the end of the container? What if you want it to be inserted in arbitrary point? What if you want to use algorithms with streams or generators?
For example, finding sum of all values in a file requires only two lines: one for declaring and opening the stream, and second for calculating sum with std::accumulate and stream iterators.
The reason is that the iterators work as interface between containers and algorithms so you can reuse the code better.

If you would have to implement all algorithms for all containers you would have to implement a total of n * m things (methods) where n is the number of containers and m the number of algorithms.

When using the iterators as interface and you only operate with those in the algorithms you only have to implement the algorithms and the containers with iterators, the amount of things (functions + iteraros) to be implemented is now n + m which is a great deal.

As a result you could just implement your own container and use all the STL algorithms.
You could also write a single algorithm on all STL containers. (for example if you want to print the content of the containers)

I watched this video, I know his english is not so good but I really like his videos.
https://www.youtube.com/watch?v=ltBdTiRgSaw&index=2&list=PL5jc9xFGsL8G3y3ywuFSvOuNm3GjBwdkb
Last edited on
You can easily wrap algorithms to take just a container.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
#include <array>
#include <deque>
#include <algorithm>

template <typename Cont>
void Sort(Cont& c)
{
	std::sort(c.begin(), c.end());
}

int main() {
	std::vector<int> v{3,5,1,9,7,2,8};
	Sort(v);
	
	std::array<int, 7> a{3,5,1,9,7,2,8 };
	Sort(a);
	
	std::deque<int> d{3,5,1,9,7,2,8 };
	Sort(d);
	
	std::cout << "v: ";
	for(const auto i : v){ std::cout << i << ' '; }
	std::cout << "\na: ";
	for(const auto i : a){ std::cout << i << ' '; }
	std::cout << "\nd: ";
	for(const auto i : d){ std::cout << i << ' '; }
}
Topic archived. No new replies allowed.