如何获取随机指针形式的指针列表?
我有简单的自定义class Buildings
和列表
std::list<Buidldings*> temp;
temp的大小大于零。如何从列表中获取随机指针(0 - temp.size)?
答案 0 :(得分:9)
使用std::rand
选择适当的索引,然后使用advance迭代器:
assert( !temp.empty() );
std::list<Buidldings*>::const_iterator it = temp.begin();
std::advance( it, std::rand() % temp.size() );
Buidldings *p = *it;
答案 1 :(得分:4)
试试这个:
template<typename ContainerType >
typename ContainerType::iterator get_random(ContainerType & container)
{
ContainerType::iterator iter = container.begin();
std::advance(iter,rand() %container.size());
return iter ;
}
template<typename ContainerType >
typename ContainerType::const_iterator get_random(const ContainerType & container)
{
... (same as above)
}
来自here