簡體   English   中英

使用C ++中的指針初始化迭代器

[英]Initialize a iterator with a pointer in C++

我在VC9中構建庫時遇到問題,但之前已在VC6中成功構建了庫。 這是代碼的一部分:

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).

有了這個,我就刪除了it迭代器並使用了lower_bound(first,last,&pos2find,comp);

那么即使在VC6中,發布的代碼也毫無意義。 但也許你正在尋找這樣的東西

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

如果沒有,那么你最好發布更多的代碼,這樣我們就可以看到你是如何嘗試使用迭代器的。

向量中的迭代器不保證是原始指針。 在VS6中, vector<T>::iterator 碰巧T*所以你可以用T*初始化迭代器。 在VS的后續版本中, vector<T>::iterator更改為類類型(因為它有權使用),因此編寫錯誤假設的代碼現在無法編譯。

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

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

我擔心你必須經歷所有代碼並修復問題,因此,正如已經指出的那樣,你的例子即使考慮到我剛寫的內容也是錯誤的。

請注意,使用指針可以使用0表示“迭代器未設置”,這與分配some_vector.end() 如果遇到類似情況,我建議您使用Boost.Optional來包裝迭代器。

在那里,完成了(但使用不同的編譯器)。

以下似乎是預期的

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);

瘋狂的代碼(一個排序的迭代器數組,真的嗎?),並且我沒有經過測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM