2013-07-02 53 views
1

我想從迭代器對創建一個stl向量,我不確定向量可能有多少個元素。它可能只有一個元素。從一對迭代器創建stl向量C++

#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; 
} 

我以爲vector'second'會有vect.begin()指向的一個元素。情況不是這樣嗎?

由於

+1

您插入0元素... – PlasmaHH

回答

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

載體構造採用開放間隔因此不即包括在端。 [first, last)

脣在他的評論中指出,這是更爲通用,以next

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

+ 1只有可用,因爲這是一個向量。更通用的語法將是'vector 秒(vect.begin(),next(vect.begin()));' – lip

+0

我試過了「vector second; std :: copy(vect.begin(),vect .begin(),std :: back_inserter(second.begin()));「但我不確定這是否有效。問題是我從另一個向量複製元素,並且可能只有一個元素指向begin() – polapts

+0

@polapts:'next(vect.begin())== vect.end()'所以可以使用我發佈的方法。 – GWW

1

號在構造函數中vector<int> second(vect.begin(), vect.begin());第二個迭代器應指向過去結束,所以你得到完全空數組。

實施例:vect.end()點恰好過去矢量vect的端,所以vector<int> second(vect.begin(), vect.end());將整個vect複製到second

3

不,事實並非如此。所述是相當清楚的:

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()); 
+0

+1。這是正確的答案和正確的解釋。間隔是右閉合的。這種能力使我們能夠表達一個空的範圍。欲瞭解更多信息,請參閱https://en.wikipedia.org/wiki/Interval_(mathematics)#Excluding_the_endpoints – Macke