c++ - Why don't std algorithms take the number of iterations as a parameter -


suppose have iterator list, , want apply algorithm next n elements in list. either have write own loop or use std::advance if want use algorithm, adds overhead.

why don't std algorithms have overloads take number of iterations perform instead of end pointer?

example:

std::list<int>::iterator it; std::list<int>::iterator out;  // desirable not possible std::copy(it, 5, out);  // defeats point of algorithms replace common loops (size_t = 0; != 5; ++i) {     *out++ = *it++; }  // unnecessary overhead std::copy(it, std::advance(it, 5), out); 

because ranges specified iterators, , iterators can formed arithmetic operations such as

f(it, + 5); 

while might cheaper specify number of iterations in cases (list example), combining iterators , iteration counts in potentially tight loops has performance cost creating scenario in easier programmers overshoot end of containers

vector<int> v { 1, 2, 3 }; for_each_eg(v, 4, [](int i) { cout << i; }); 

with strategy, wind spending lot more time doing constraint checking. in practice it's lot easier right thing in first place when sticking iterators , ranges.

f(v, v.size()); 

vs

f(v.begin(), v.end()); 

doesn't sell idea much, consider how second adapts to:

f(v.rbegin(), v.rend()); 

i leave exercise reader think how implement using first syntax.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -