以下文字来自 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/