pep*_*ero 0 c++ arrays pointers stl vector
我对指针和迭代器一无所知,特别是在从数组构造向量的情况下.
从对矢量的描述来看,它说
// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
Run Code Online (Sandbox Code Playgroud)
在初级,它是:
#include <vector>
int arr[ARR_LEN] = { /* Array elements */ };
std::vector<int> vecInt(arr, arr + ARR_LEN);
Run Code Online (Sandbox Code Playgroud)
它使用以下构造函数?
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)
如果是这样,那么这里是一个指针(对于数组)处理成随机访问迭代器,然后作为输入迭代器?编译器如何做到这一点?考虑来自其他容器的迭代器,这个迭代器的类型是什么,例如"array [int]":: iterator?
int arr[N] = {};
for (int i= 0; i<N; i++) {}
Run Code Online (Sandbox Code Playgroud)
而不是上述,我可以做如下的事情吗?
for (ItorType it=arr; it!=arr+N; ++it) { ... }
Run Code Online (Sandbox Code Playgroud)
迭代器模板参数不是特定的类.实际上,这些名称对编译过程没有实际影响.相反,它们指的是指定特定迭代器可用方法的特定概念.任何RandomAccessIterator也必须是InputIterator:RandomAccessIterator概念是InputIterator概念的改进.
编译器实际上只是传递这些参数,在你的情况下指针,通过.指针实现RandomAccessIterator概念,即它们可以很容易地与std::vector<...>您引用的构造函数一起使用.顺便说一下,写这个初始化的正确方法是
std::vector<int> vecInt(std::begin(arr), std::end(arr));
Run Code Online (Sandbox Code Playgroud)
该函数模板begin(),并end()添加到C++的最新版本,并推断出静态大小的数组的大小.用于确定示例中的大小的两种方法在某些方面都存在问题.
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |