我有一段代码可以为玩家生成小任务。这很简单,要获得两个不同的点(起点和终点),我有一个如下所示的算法:
std::vector<std::string> missions;
missions.push_back("Location_One");
missions.push_back("Location_Two");
missions.push_back("Location_Three");
//make sure our data has at least 2 elements (so we can actually pick two)
if(missions.size() > 1)
{
//Rand(inclusive min, exlusive max)
int mission_start_location = Rand(0,missions.size());
int mission_end_location = Rand(0,missions.size());
if(mission_start_location == mission_end_location)
{
//avoid possile infinite loop of calling "Rand" by Add/Decrement-if-equal algorithm
//basicly if mission_start_location == 0
if(!mission_start_location)
++mission_end_location;//or = 1, we have at least two elements so index 1 is valid
else
--mission_end_location;//so we won't got out of range
}
//do mission
}
else
{
//error
}
这行得通,但是我想知道是否有更好的方法来实现我想要的,“C++ 方式”。
我的问题是:
- 这是从容器中获取两个不同值的最佳方法吗?
- 非整数索引容器(例如
std::map<std::string,std::string>
)呢? - 我如何从中获得两个不同的随机值?
注意:我非常了解这种do { } while(rand1 == rand2)
方法。我想避免这种情况,因为它可以进入无限循环(知道我的运气会在生产代码中)。