我想初始化一个映射 - 对象“id”,其身份从 0 到 n-1,即
id[0] = 0
id[1] = 1
.
.
id[n-1] = n-1
有没有一种简单的方法 - 单线,地图对象内的方法,只是非常简单的东西 - 可以做到吗?
出什么问题了
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);