(i'm sorry.im not good in english.im iranian) we know that the purpose of oop is merging data structures and algorithms to provide a single entity.so the STL separates them.why STL didn't write their own methods as member functions??
Asked
Active
Viewed 255 times
2
-
10Because N algorithms + M data structures is less code to write than N algorithms * M data structures. – milleniumbug Oct 06 '16 at 15:08
-
2Why not write an algo that anyone can use instead of making you write your own since there is not a generic function. – NathanOliver Oct 06 '16 at 15:09
-
1If you make an algorithm a member function you can't re-use it for other objects that behave in a similar way. – Galik Oct 06 '16 at 15:10
-
The STL was never OOP. Because Stepanov is smart. – Barry Oct 06 '16 at 15:13
-
It is not really data structures (in general) and algorithms that are separated (most `std` structures do contain some methods!). For the most part, it is _container types_ and algorithms that are separated. – mindriot Oct 06 '16 at 15:13
1 Answers
4
Consider implementing what you're suggesting - every data structure would have to re-implement every algorithm:
template <typename T>
class vector
{
auto for_each(/* ... */) { /* ... */ }
auto partition(/* ... */) { /* ... */ }
auto sort(/* ... */) { /* ... */ }
/* ... */
};
template <typename T>
class list
{
auto for_each(/* ... */) { /* ... */ }
auto partition(/* ... */) { /* ... */ }
auto sort(/* ... */) { /* ... */ }
/* ... */
};
template <typename TK, typename TV>
class map
{
auto for_each(/* ... */) { /* ... */ }
auto partition(/* ... */) { /* ... */ }
auto sort(/* ... */) { /* ... */ }
/* ... */
};
As you can see, there is severe code duplication. Also, this approach is unmaintainable, as adding a new algorithm will require the implementation of every container to be changed.
If UFCS is going to be accepted into the standard alongside ranges, then you will be able to call algorithms on standard containers as if they were member functions:
std::vector<int> v{/* ... */};
v.sort(); // Actually calls `std::sort(v)` thanks to UFCS.

Vittorio Romeo
- 90,666
- 33
- 258
- 416