[英]`iterator` and `const_iterator` for C arrays in C++?
Is there a way to get either an iterator
and a const_iterator
from both C arrays and C++ STL containers? 有没有办法从C数组和C ++ STL容器中获得
iterator
和const_iterator
?
I have this template: 我有这个模板:
template <typename T>
class Another_template {
// implementation
};
template <typename Container>
Another_template<typename Container::iterator>
fun(Container&) {
// implementation
}
I would like the above function to work for C arrays, too. 我也希望以上函数也可用于C数组。 Is it possible?
可能吗? Or should I specialize it for C arrays?
还是应该专门针对C数组?
I know that C++ has std::array
, but I am curious about C arrays. 我知道C ++具有
std::array
,但是我对C数组感到好奇。
You may use standard functions std::begin
, std::end
, std::cbegin
, std::cend
declared in header <iterator>
with arrays and standard containers. 您可以将标头
<iterator>
声明的标准函数std::begin
, std::end
, std::cbegin
, std::cend
std::cbegin
与数组和标准容器一起使用。
Here is a demonstrative program 这是一个示范节目
#include <iostream>
#include <iterator>
#include <vector>
template <typename Container>
auto f( const Container &c ) ->decltype( std::begin( c ) )
{
for ( auto it = std::begin( c ); it != std::end( c ); ++it )
{
std::cout << *it << ' ';
}
std::cout << std::endl;
return std::begin( c );
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
f( a );
std::vector<int> v = { 1, 2, 3, 4, 5 };
f( v );
return 0;
}
The output is 输出是
1 2 3 4 5
1 2 3 4 5
EDIT: You changed your original code snippet nevertheless you may use the same approach. 编辑:尽管如此,您仍更改了原始代码段,但是您可以使用相同的方法。 Here is an example
这是一个例子
template <typename Container>
auto f1( const Container &c ) ->std::vector<decltype( std::begin( c ) )>;
如果需要C数组的功能,则可以使用stl向量,并通过获取对第一个元素的引用来像ac数组一样使用它:
int *c_array = &my_int_vector[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.