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

pol*_*pts 1 c++ stl stdvector

我试图从迭代器对创建一个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;
}
Run Code Online (Sandbox Code Playgroud)

我认为向量'second'将有一个由vect.begin()指向的元素.不是这样吗?

谢谢

GWW*_*GWW 6

vector<int> second(vect.begin(), vect.begin() + 1);
Run Code Online (Sandbox Code Playgroud)

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

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

second(vect.begin(), next(vect.begin()));
Run Code Online (Sandbox Code Playgroud)

  • + 1仅可用,因为这是一个向量.更通用的语法是`vector <int> second(vect.begin(),next(vect.begin()));` (2认同)