从迭代器c++对创建stl向量

Creating stl vector from pair of iterator c++

本文关键字:stl 向量 创建 迭代器 c++      更新时间:2023-10-16

我正试图从迭代器对创建一个stl向量,但我不确定该向量可能有多少元素。它只能有一个元素。

#include <iostream>
#include <vector>
int main()
{
    using namespace std;
    vector<int> vect;
    for (int nCount=0; nCount < 6; nCount++)
        vect.push_back(nCount);
    vector<int> second(vect.begin(), vect.begin() );
    vector<int>::iterator it; // declare an read-only iterator
    it = second.begin(); // assign it to the start of the vector
    while (it != second.end()) // while it hasn't reach the end
    {
        cout << *it << " "; // print the value of the element it points to
        it++; // and iterate to the next element
    }
    cout << endl;
}

我以为向量"second"会有一个元素被vect.begin()指向。事实不是这样吗?

感谢

vector<int> second(vect.begin(), vect.begin() + 1);

向量构造函数使用开放区间,因此不包括结束,即[first, last)

正如lip在评论中指出的那样,它更通用于next:

second(vect.begin(), next(vect.begin()));

不,事实并非如此。文档非常清晰:

template< class InputIt > 
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)    

4) 构造具有范围[首先,最后)。

符号"[第一,最后)"表示复制firstlast之间但不包括last的所有元素。由于first==last,因此不复制任何元素。

进一步阅读文档,您似乎可以使用另一个构造函数:

explicit vector( size_type count, 
                 const T& value = T(),
                 const Allocator& alloc = Allocator());  (until C++11)
         vector( size_type count, 
                 const T& value,
                 const Allocator& alloc = Allocator());  (since C++11)

这样:

vector<int> second(1, vect.front());

否。在构造函数vector<int> second(vect.begin(), vect.begin());中,第二个迭代器应该指向超过的末尾,这样您就得到了完全为空的数组。

示例:vect.end()正好指向向量vect的末尾,因此vector<int> second(vect.begin(), vect.end());会将整个vect复制到second中。