STL algorithms taking the whole container rather than .begin(), end() as arg?

房东的猫 提交于 2019-11-29 16:50:49

问题


Stand-alone STL algorithms (like std::count_if) take pair of iterators. In all cases where I use those (and in all examples I've seen online!), I find myself typing

std::count_if(myContainer.begin(),myContainer.end(), /* ... */ );

Is there a reason why shorthand templates of the style

std::count_if(myContainer, /* ... */ );

are not provided, given that more of than not is the operaation performed on the whole container? Did I just overlook it? Is the answer different for c++11 and c++03?


回答1:


There is a nice blog-post by Herb Sutter discussing the question. The gist is that adding container-based overloads for algorithms can create ambiguities if an overload for that algorithm with the same number of template-parameters already exists. Concepts were intended to fix that problem.




回答2:


One reason could be to provide the flexibility for iterator range. You may not need to iterate through all elements sometime:

<iterator> it = myContainer.begin();
it++; // do something
it++; // do something
...
std::count_if(it, myContainer.end(), /* ... */ );

Also, you can always have a wrapper which does this for you:

template<typename T>
... count_if (T myContainer, ...)
{
  std::count_if(myContainer.begin(), myContainer.end(), /* ... */ );
}



回答3:


STL principle and flexibility is mainly because of operating on iterators instead of containers. It is not a big problem, you can re-use trick I am using from my early C years:

#define FULL_RANGE(c) (c).begin(), (c).end()

std::copy(FULL_RANGE(c), std::ostream_iterator<c::value_type>(cout, "\n")); 



回答4:


Simply because STL algorithms are connected / talks with container using iterators.



来源:https://stackoverflow.com/questions/8164738/stl-algorithms-taking-the-whole-container-rather-than-begin-end-as-arg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!