C++ - 在需要 Iterator 类型的 vector (或其他容器)构造函数中使用数组/指针。这怎么可能?

标签 c++ arrays pointers vector

以下文字来自 C++ 在线类(class)。它说 vector 类的构造函数

 template <class InputIterator>
          vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );

可以接收指针作为第一个(InputIterator first)和第二个参数(InputIterator last)。

The next constructor uses iterators to initialize itself. It will create a vector with a copy of values from first (inclusive) to last (exclusive). In the most typical case, this constructor creates a new vector using elements from an already existing collection. But due to the fact that iterators are defined as a set of operations instead of a certain type, it is also possible to use normal pointers. This remark leads to a conclusion that you can use a normal C++ array to initialize a collection. And in fact you can.

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    int a1[]={1,2,3,4,5,6,7,8,9,10};
    //first one
    vector<int> v1(a1, a1+10);
    cout<<"Size (v1):  "<<v1.size()<<endl;
    for(unsigned i = 0; i < v1.size(); ++i)
    {
        cout<< v1[i]<<" ";
    }
    cout<<endl;
    //second one;
    vector<int> v2(a1+5,a1+10);
    cout<<"Size (v2):  "<<v2.size()<<endl;
    for(unsigned i = 0; i < v2.size(); ++i)
    {
        cout<< v2[i]<<" ";
    }
    cout<<endl;
    return 0;
}

我可以习惯这一点,但我真的不明白为什么这是可能的。我想了解这项技术。

我在这种情况下的问题(见代码)是我怎么可能简单地放置一个数组地址而不是迭代器?

在上面的代码中,int * 类型的元素被作为 InputIterator 类型的参数。这让我很困惑。

最佳答案

所有的故事都是关于构造对迭代器的期望。它希望能够递增它(使用++),顺从它(使用 *)。 interator 要么是重载++ 和 * 运算符的类,要么是自然支持这两种操作的基本指针类型。

关于C++ - 在需要 Iterator 类型的 vector (或其他容器)构造函数中使用数组/指针。这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31480671/

相关文章:

c++ - 编辑控件中的可点击链接

c++ - 函数调用中参数前的双哈希

c++ - 如何在C++中取每第n个元素的平均值

javascript - 如何根据另一个数组中的相应值对一个数组进行排序?

arrays - 在排序数组中查找索引

c++ - 指针是如何工作的

c++ - 与编译器无关的 Fortran 名称修改功能

javascript排序和重新映射数组

c++ - 没有 [ ] 的数组等于什么? C++

c - 链表在开头打印额外的 0