[英]What's the simplest way to create an STL - identity map?
我想初始化一個地圖 - 對象“id”,其身份從0到n-1,即
id[0] = 0
id[1] = 1
.
.
id[n-1] = n-1
有一個簡單的方法 - 一個單行,一個方法在map-object中,只是一些非常簡單的東西 - 這樣做?
出什么問題了
for(unsigned int i = 0; i < n; ++i)
id[i] = i;
你可以使用
template <class InputIterator>
map(InputIterator f, InputIterator l,
const key_compare& comp)
構造函數的形式,但您需要構建一個InputIterator,它在您想要的范圍內充當生成器函數。 這比單獨使用for循環要多得多。
使用密鑰為簡單索引的地圖似乎有點奇怪。 你確定你不能使用矢量嗎? 這樣做,您可以使用boost::counting_iterator
來填充向量:
std::vector<int> v(boost::counting_iterator<int>(0),
boost::counting_iterator<int>(N-1));
// v is filled with integers from 0 to N-1
但是,與簡單的for循環相比,我不確定這是否是一個巨大的收獲。
請注意std :: iota作為數字庫的一部分(C ++ 0x特性):
template <ForwardIterator Iter, HasPreincrement T>
requires OutputIterator<Iter, const T&>
void iota(Iter first, Iter last, T value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.