我可以在非标准容器上使用迭代器库的访问函数吗? [英] Can I use the iterator Libraries' Access Functions on Nonstandard Containers?
问题描述
迭代器
库已经引入了大量的访问函数:
-
begin $
/ code> /
cend
-
crbegin
/crend
-
data
-
empty
-
rbegin
/rend
-
size
我使用这些在任何容器,甚至非标准的容器(只要他们提供一个可访问的相应的方法?)例如给定一个 QVector
foo
我可以这样做:
const auto bar = begin(foo);
解决方案 std的声明: :begin
如下(从&; 24.7):
template< class C&自动开始(C& C) - > decltype(c.begin());
template< class C> auto begin(const C& c) - > decltype(c.begin());
因此,这些函数将被定义为任何类 C
使得 c.begin()
是有效(确实存在)。该标准还保证这些将:
返回: c.begin
因此是可以使用 begin (c) C
的任何容器
$ <$ p
b $ b 提供了成员函数 C :: begin()
。
存在 begin(C const&)
或 begin(C&)
function。
独立的 begin
函数不应在 std ::
命名空间中,在与您的类 C
相同的命名空间中,因此名称查找可以找到它。
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);
解决方案 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&)
or begin(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.
这篇关于我可以在非标准容器上使用迭代器库的访问函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!