Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从迭代器c++;_C++_Stl_Stdvector - Fatal编程技术网

C++ 从迭代器c++;

C++ 从迭代器c++;,c++,stl,stdvector,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); vec

我试图从迭代器对创建一个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;
}
#包括
#包括
int main()
{
使用名称空间std;
向量向量;
对于(int-nCount=0;nCount<6;nCount++)
向量推回(n计数);
向量秒(vect.begin(),vect.begin());
vector::iterator;//声明只读迭代器
it=second.begin();//将其指定给向量的开头
while(it!=second.end())//当它还没有到达终点时
{

coutNo.在构造函数
vector second(vect.begin(),vect.begin());
第二个迭代器应该指向末尾,所以得到的数组正好是空的


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

不,情况并非如此。原因非常清楚:

template< class InputIt > 
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)    
…以这种方式:

vector<int> second(1, vect.front());
向量秒(1,vect.front());
您插入0个元素…+1仅可使用,因为这是一个向量。更通用的语法是
向量秒(vect.begin(),next(vect.begin());
我尝试了“向量秒;std::copy(vect.begin(),vect.begin(),std::back\u inserter(second.begin());”但我不确定这是否有效。问题是我正在从另一个向量复制元素,其中可能只有一个元素由begin()@polapts:
next(vect.begin())==vect.end()
指向,所以可以使用我发布的方法。如果要添加多个元素,那么我是否必须使用if(std::distance)之类的if条件(itBegin,itEnd)>1)然后是第二个(vect.begin(),vect.end());否则是第二个(vect.begin(),next(vect.begin());?+1。这是正确的答案,有正确的解释。间隔是右闭合的。此功能允许我们表示一个空范围。有关更多信息,请参阅
template< class InputIt > 
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)    
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());