我有一个由汽车品牌ID和相关车型组成的列表,例如:
1个花冠
1 Yaris
1个矩阵
2名切诺基人
2自由
3 CR-V
3 CR-Z
3个元素
3个城市
3名飞行员
其中包括1=Toyota、2=Jeep和3=Honda。请注意,每个汽车品牌的汽车型号的基数不同。
我想检索每个汽车品牌的随机车型。每个汽车品牌要检索的汽车数量取决于关联车型的总数和输入浮点参数:'nPercentage‘。( 'nPercentage‘参数对于所有不同的汽车品牌都是相同的)。例如,如果为nPercentage=0.5,则可能的随机输出为:
1个花冠
1个矩阵
2自由
3 CR-Z
3个城市
3名飞行员
我目前正在使用一个multimap类,因为键可以复制。到目前为止,我能够找到未重复的键并计算相关元素的数量。有人能解释一下如何检索每个汽车品牌的随机车型吗?下面是我到目前为止拥有的代码。
//The variable 'm_mapDatasetMapping' is of type: multimap<int, string>
multimap< int, string >::size_type countPerKey;
const int *pLastKey = NULL;
multimap<int,string>::const_iterator it=m_mapDatasetMapping.begin();
// looking for non-duplicated keys.
for( ; it!=m_mapDatasetMapping.end(); it++){
if( (pLastKey!=NULL) && (*pLastKey==it->first) ){
continue;
}
pLastKey = &(it->first);
// count the number of values associated to the given key.
countPerKey = m_mapDatasetMapping.count(*pLastKey);
/* Select 'x' random elements associated with the key '*pLastKey'.
The number of random elements to be extracted
is a percentage of the total number of values per key, i.e.:
x = nPercentage * countPerKey
*/
...
}发布于 2011-03-23 21:40:19
也许最简单的方法是将给定键的所有值复制到一个新的容器中,比如vector,random_shuffle它,然后resize()它以将它的大小减少到x:
int x = nPercentage * countPerKey;
auto range = m_mapDatasetMapping.equal_range(*pLastKey);
std::vector<std::string> values;
for(auto i = range.first; i != range.second; ++i)
values.push_back(i->second);
std::random_shuffle(values.begin(), values.end());
values.resize(x);https://stackoverflow.com/questions/5405923
复制相似问题