需求: 存在N个互斥事件,每个事件都有自己的触发概率。依据这些概率,随机触发事件。 #include <iostream> #include <vector> #include <time.h> using namespace std; const unsigned Denominator = 0xfff; template<typename T> class RandValue { public: RandValue(T value,float probability) { _value = value; _prob = probability; } float GetProbability(); T GetValue(); private: T _value; //事物 float _prob;//概率 }; template<typename T> float RandValue<T>::GetProbability() { return _prob; } template<typename T> T RandValue<T>::GetValue() { return _value; } template<typename T>//rand随机种子[0-1] bool GetRand(const vector<RandValue<T> *>* vec, float rand, T &result) { int count = vec->size(); float f_temp = 0; RandValue<T> * rv = NULL; for(int i = 0; i < count; i++) { rv = (*vec)[i]; f_temp += rv->GetProbability(); if(rand < f_temp) { result = rv->GetValue(); return true; } } return false; } int main() { vector<RandValue<int>*> vec; vec.push_back( &RandValue<int>(5,0.5f)); vec.push_back( &RandValue<int>(4,0.2f)); vec.push_back( &RandValue<int>(3,0.1f)); vec.push_back( &RandValue<int>(2,0.2f)); int result = 0; float rand_value; srand((unsigned)time(NULL)); for (int i = 0; i < 10; i++) { rand_value = (float)(rand()%Denominator)/(float)Denominator; GetRand(&vec,rand_value,result); cout<<rand_value<<": "<<(int)result<<endl; } getchar(); return 0; }