“迭代器”和“const_iterator”表示 C++ 中的 C 数组
`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数组很好奇。
您可以使用标准函数std::begin
、std::end
、std::cbegin
、std::cend
在带有数组和标准容器的标头<iterator>
中声明。
这是一个演示程序
#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 向量,并通过获取对第一个元素的引用来像 c 数组一样使用它:
int *c_array = &my_int_vector[0];
相关文章:
- 在C++程序中使用的迭代器中未处理的异常
- 如何在目录迭代器中选择特定的目录条目
- 为什么我们不在 STL 的迭代器中传递星号(*)
- 为什么我不能在 c++ 中"map"的迭代器中使用"+1"?
- 如何从迭代器中找到对的类型
- 访问存储在迭代器中的数据
- Cygwin目录迭代器中的Boost文件系统
- 通过C 中的迭代器中的集合中的集合
- 使用迭代器中的库存中的项目计数器
- 列表<对象*>迭代器中的分段错误
- C :在多迭代器中的Next()和PRAV()的运行时间
- 从迭代器中的功能指针调用功能
- 双端的迭代器中的错误
- 为什么我的 forloop 在我的 lexical_words 函数中没有将字符串数组('keyWords")中的单词与字符串迭代器中的单词进行比较?
- C++-映射迭代器中的if语句导致程序崩溃的原因
- 如何编写一个迭代器包装器来组合底层迭代器中的顺序值组
- std::list迭代器中的分段错误
- 数组迭代器中的hasNext()方法
- 迭代器中的非标准语法错误?(c++)
- 迭代器中的矢量迭代器错误