【问题标题】:Creating stl vector from pair of iterator c++从一对迭代器 c++ 创建 stl 向量
【发布时间】:2013-07-02 14:14:39
【问题描述】:

我正在尝试从迭代器对创建一个 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;
}

我认为向量“第二个”将有一个由 vect.begin() 指向的元素。不是这样吗?

谢谢

【问题讨论】:

  • 你插入了 0 个元素...

标签: c++ stl stdvector


【解决方案1】:
vector<int> second(vect.begin(), vect.begin() + 1);

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

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

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

【讨论】:

  • + 1 仅可用,因为这是一个向量。更通用的语法是 vector&lt;int&gt; second(vect.begin(), next(vect.begin()));
  • 我试着做“vector second; std::copy(vect.begin(), vect.begin(), std::back_inserter(second.begin()));”但我不确定这是否有效。问题是我正在从另一个向量复制元素,其中可能只有一个元素由 begin() 指向
  • @polapts: next(vect.begin()) == vect.end() 所以用我贴的方法就可以了。
  • 如果要添加多个元素,那么我是否必须使用 if 条件,例如 if(std::distance(itBegin, itEnd) >1) then second(vect.begin(), vect.end()); else second(vect.begin(), next(vect.begin()));?
【解决方案2】:

不,事实并非如此。 documentation 很清楚:

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

4) 用范围 [first, 最后)。

符号“[first, last)”表示复制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());

【讨论】:

  • +1。这是正确解释的正确答案。区间是右闭的。这种能力允许我们表达一个空的范围。有关详细信息,请参阅en.wikipedia.org/wiki/…
【解决方案3】:

没有。在构造函数 vector&lt;int&gt; second(vect.begin(), vect.begin()); 中,第二个迭代器应该指向 过去 末尾,所以你会得到完全空的数组。

示例:vect.end() 恰好指向向量vect 的末尾,因此vector&lt;int&gt; second(vect.begin(), vect.end()); 会将整个vect 复制到second

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 2020-11-06
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多