问题
The iterator
library has been introducing a lot of access functions over the course of C++11, C++14, and C++17:
begin
/end
cbegin
/cend
crbegin
/crend
data
empty
rbegin
/rend
size
Can I use these on any container, even nonstandard containers (provided they supply an accessible corresponding method?) For example given a QVector foo
can I do this:
const auto bar = begin(foo);
回答1:
The declarations for std::begin
are as follow (from §24.7):
template <class C> auto begin(C& c) -> decltype(c.begin());
template <class C> auto begin(const C& c) -> decltype(c.begin());
So these functions will be defined for any class C
such that c.begin()
is "valid" (does exist). The standard also guarantees that these will:
Returns:
c.begin()
.
So yes you can use begin(c)
on any container of type C
as long as either:
- The member function
C::begin()
is provided. - There exist a
begin(C const&)
orbegin(C &)
function.
The standalone begin
function should not be in the std::
namespace but rather in the same namespace as your class C
so name-lookup can find it.
回答2:
As I understand it, your question seem to be: if the container provides a member function begin
, can I then call it as a free function? The answer to your question is yes, because a templated free function begin is provided by the standard, that simply tries to call the member function begin; from http://en.cppreference.com/w/cpp/iterator/begin: "Returns an iterator to the beginning of the given container c or array array. These templates rely on C::begin()
having a reasonable implementation.".
来源:https://stackoverflow.com/questions/38101301/can-i-use-the-iterator-libraries-access-functions-on-nonstandard-containers