[英]`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.