【发布时间】:2016-07-17 12:51:38
【问题描述】:
切入正题:以下安全吗?
vector<int> v;
int const* last = &*v.end();
// last is never dereferenced
我担心的是,从迭代器中获取普通旧指针的技巧会强制取消对 end() 迭代器的引用,这是无效的……即使只是为了取回指针!
背景:我正在尝试创建一个由任意类型(尤其是整数和指向对象的指针)索引的条目集合。
template<class IT>
/// requires IT implements addition (e.g. int, random-access iterator)
class IndexingFamily {
public:
using IndexType = IT;
IndexingFamily(IndexType first, IndexType last);
int size() const;
IndexType operator[](int i) const;
private:
IndexType first;
IndexType last;
};
template<class IT> IndexingFamily<IT>::
IndexingFamily(IndexType first, IndexType last)
: first(first)
, last(last) {}
template<class IT> auto IndexingFamily<IT>::
size() const -> int {
return last-first;
}
template<class IT> auto IndexingFamily<IT>::
operator[](int i) const -> IndexType {
return first+i;
}
template<class IT, class ET>
struct IndexedEntry {
using IndexType = IT;
using EntryType = ET;
IndexType index;
EntryType entry;
};
template<class IT, class ET>
class CollectionOfEntries {
public:
using IndexType = IT;
using EntryType = ET;
/// useful methods
private:
IndexingFamilyType indexingFamily;
vector<EntryType> entries;
};
struct MyArbitraryType {};
int main() {
MyArbitraryType obj0, obj1, obj2;
vector<MyArbitraryType> v = {obj0,obj1,obj2};
using IndexType = MyArbitraryType const*;
IndexingFamily<IndexType> indexingFamily(&*v.begin(),&*v.end());
using EntryType = double;
using IndexedEntryType = IndexedEntry<IndexType,EntryType>;
IndexedEntry entry0 = {&obj0,42.};
IndexedEntry entry1 = {&obj1,43.};
vector<IndexedEntryType> entries = {entry0,entry1};
CollectionOfEntries coll = {indexingFamily,entries};
return 0;
}
【问题讨论】:
-
FWIW,“由任意类型索引的条目集合”听起来很像地图的定义...
-
v.data() + v.size()会更安全。 -
您知道
end()指的是最后一个元素,对吧? -
@OliverCharlesworth 是的,但在我的真实案例中,地图对处理数据的方式没有帮助
-
@JesperJuhl 是的,理想情况下,我想要 vector
::const_iterator == T const*