c++ - 没有模板的 std::array 迭代器范围?

标签 c++ arrays iterator

使用 C 数组,编写采用任意大小数组的代码相当容易:

void func( T* itBegin, T* itEnd );

void main() {
    T arr1[1];
    func( std::begin(arr1), std::end(arr1) );
    T arr2[2];
    func( std::begin(arr2), std::end(arr2) );
}

我如何使用 std::arrays 做到这一点?

void func( ??? itBegin, ??? itEnd );

void main() {
    std::array<T,1> arr1;
    func( std::begin(arr1), std::end(arr1) );
    std::array<T,2> arr2;
    func( std::begin(arr2), std::end(arr2) );
}

问题是,在 MSVC 2010 中,std::array<T,N>::iterator不同N不同.这是 MSVC 2010 中的错误吗?如果不是,这种设计的基本原理是什么?是的,我可以从 std::array 获取指针并传递它们而不是迭代器,但这不是不必要的丑陋吗?

顺便说一句,boost::array<T,N>::iterator所有N都是一样的.

最佳答案

template <class I>
void func(I begin, I end)
{
    for (auto x = begin; x != end; ++x)
        something_with(*x);
}

将它们一般地定义为类型参数,然后就像使用指针一样使用它们。任何行为类似于指针的东西都会编译,否则不会编译。

类似指针的东西包括普通指针、标准库迭代器和任何其他定义 operator= 的东西, operator*operator++ .

以这种方式进行操作,因为您只会使用来自相同 array<N> 的开始/结束迭代器范围的匹配对。 , 那么 array<N>::iterator 就没关系了是与 array<M>::iterator 不同的类型.

关于c++ - 没有模板的 std::array 迭代器范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10189191/

相关文章:

c++ - 如何使用 SimpleIni 返回 wchar_t 然后转换为 std::wstring?

c++ - 在 dll 中使用 std::list 无法解析的外部符号

java - 为什么 hasNextInt() 在这里返回 false ?

c++ - < 遍历 C++ 映射时缺少运算符

c++ - 类方法访问它的数据成员

c++ - 我应该使用 std::for_each 吗?

php - 在 php 中分割 <b>

php - 在PHP中的每个级别递归排序多维数组

c++ - 来自 Iterator 定义的 ConstIterator

pandas - 迭代 Groupby 对象的字段