[英]`iterator` and `const_iterator` for C arrays in C++?
有没有办法从C数组和C ++ STL容器中获得iterator
和const_iterator
?
我有这个模板:
template <typename T>
class Another_template {
// implementation
};
template <typename Container>
Another_template<typename Container::iterator>
fun(Container&) {
// implementation
}
我也希望以上函数也可用于C数组。 可能吗? 还是应该专门针对C数组?
我知道C ++具有std::array
,但是我对C数组感到好奇。
您可以将标头<iterator>
声明的标准函数std::begin
, std::end
, std::cbegin
, std::cend
std::cbegin
与数组和标准容器一起使用。
这是一个示范节目
#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;
}
输出是
1 2 3 4 5
1 2 3 4 5
编辑:尽管如此,您仍更改了原始代码段,但是您可以使用相同的方法。 这是一个例子
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.