2011-08-22 78 views
2

我在VC9中構建庫時遇到了問題,但之前成功構建於VC6中。 下面是代碼的一部分:使用C++中的指針初始化迭代器

size_t pos2find; 
pos2find = J; 
std::vector<size_t>::iterator it(&pos2find); 

這裏是錯誤:

error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'size_t *' to 'const std::_Vector_iterator<_Ty,_Alloc> &' 
    1>  with 
    1>  [ 
    1>   _Ty=size_t, 
    1>   _Alloc=std::allocator<size_t> 
    1>  ] 
    1>  Reason: cannot convert from 'size_t *' to 'const std::_Vector_iterator<_Ty,_Alloc>' 

1>  with 
1>  [ 
1>   _Ty=size_t, 
1>   _Alloc=std::allocator<size_t> 
1>  ] 
1>  No constructor could take the source type, or constructor overload resolution was ambiguous 

我感謝所有幫助。

編輯: 該代碼來自一個名爲「surfit」的開源庫,它不是我的代碼,所以我猜這是在矢量類的標準中發生了變化。 迭代器,然後在另一個STD功能使用:

std::vector<size_t>::iterator * ptr_from = fault->sort_by_first_begin; 
std::vector<size_t>::iterator * ptr; 
ptr = std::lower_bound(ptr_from, 
       fault->sort_by_first_end, 
       it, 
       ptr_size_t_less); 

編輯: 我想我找到了解決辦法。尋找到的std ::後LOWER_BOUND():

template <class ForwardIterator, class T, class Compare> 
    ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, 
           const T& value, Compare comp); 

Return iterator to lower bound 
Returns an iterator pointing to the first element in the sorted range [first,last) which does not compare less than value. The comparison is done using either operator< for the first version, or comp for the second. 

For the function to yield the expected result, the elements in the range shall already be ordered according to the same criterion (operator< or comp). 

有了這個,我只是消除了它的迭代器和使用LOWER_BOUND(第一,最後,& pos2find,COMP);

+1

作爲一個常規提示:msvc6是如此的破壞和預標準,以致爲它編寫的大量代碼將不能用符合標準的編譯器進行編譯。它甚至不支持正確的循環變量範圍,直到後來的某個Service Pack。 – PlasmaHH

+0

我想盡可能多。但是,也許有人認爲這種情況有一個解決方法。 – Adrian

回答

4

向量中的迭代器不保證是一個原始指針。在VS6中vector<T>::iterator發生了T*,因此您可以使用T*初始化迭代器。 在較新版本的VS中,vector<T>::iterator的實現更改爲類類型(因爲它有權使用),因此做出錯誤假設的代碼現在無法編譯。

在任何情況下,即使iteratorT*,您發佈的代碼也是錯誤的,因爲提供的指針不是指向矢量的指針。

4

那麼,即使在VC6中,發佈的代碼也沒有任何意義。但是,也許你正在尋找這樣的事情

std::vector<size_t>::iterator it = some_vector.begin() + pos2find; 

如果沒有,那麼你最好張貼更多的代碼,所以我們可以看到你如何試圖使用迭代器。

+0

我希望是這種情況,但迭代器然後用於從標準更復雜的方法。 – Adrian

+0

@阿德里安,看到我的新嘗試來解釋這一點。 – john

2

原始代碼依賴於標準沒有保證的實現細節,即迭代器可以實現爲指針的事實。我不確定這是否仍然如此,但是在更高版本的Visual C++中實現更改爲特定的類模板。

恐怕你必須經歷所有的代碼和解決的事情,更何況,因爲它已經被指出的那樣,你的例子是越野車即使考慮到我剛纔寫的。

要注意的是使用指針,你可以用0表示「迭代器沒有設置」,這將是從分配some_vector.end()不同。如果遇到類似的情況,我建議你使用Boost.Optional來包裝你的迭代器。

去過那裏,這樣做(但使用不同的編譯器)。

1

下似乎什麼打算

std::vector<size_t> tmp; 
tmp.push_back(J); 
std::vector<size_t>::iterator it = tmp.begin(); 

std::vector<size_t>::iterator * ptr_from = fault->sort_by_first_begin; 
std::vector<size_t>::iterator * ptr; 
ptr = std::lower_bound(ptr_from, 
       fault->sort_by_first_end, 
       it, 
       ptr_size_t_less); 

瘋狂代碼(迭代器的排序陣列,真的嗎?),並且未經我測試。

+0

是的,這是一個好主意,但只是發現我可以用&pos2find替換它。感謝您的支持。 – Adrian