用C++从迭代器对创建stl向量

3

我正在尝试从迭代器对创建一个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()指向的元素。不是这样吗?谢谢。

1
您插入了0个元素... - undefined
3个回答

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

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

正如Lip在他的评论中指出的那样,使用next更加通用:

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

2
  • 1之所以可用,是因为这是一个向量。更通用的语法将是 vector<int> second(vect.begin(), next(vect.begin()));
- undefined
我尝试使用以下代码进行复制操作:"vector<int> second; std::copy(vect.begin(), vect.begin(), std::back_inserter(second.begin()));" 但是我不确定这是否有效。问题在于我正在从另一个向量中复制元素,而且可能只有一个由begin()指向的元素。 - undefined
@polapts:next(vect.begin()) == vect.end(),所以可以使用我发布的方法。 - undefined
如果要添加多个元素,我是否需要使用if条件语句,例如if(std::distance(itBegin, itEnd) > 1),然后执行second(vect.begin(), vect.end());否则执行second(vect.begin(), next(vect.begin()))? - undefined

3
不,事实并非如此。文档相当清晰明了
template< class InputIt > 
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)    

构造函数使用 [first, last) 范围内的内容构建容器。
注释 "[first, last)" 表示复制 first 和 last 之间但不包括 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());

+1. 这是正确的答案,附有适当的解释。区间是右闭合的。这种能力使我们能够表示一个空范围。有关更多信息,请参阅https://en.wikipedia.org/wiki/Interval_(mathematics)#Excluding_the_endpoints - undefined

2
在构造函数中,vector<int> second(vect.begin(), vect.begin());的第二个迭代器应该指向结束位置,这样才能得到一个确切的空数组。
例如:vect.end() 指向向量 vect 的结束位置,所以 vector<int> second(vect.begin(), vect.end()); 将整个 vect 复制到 second 中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接