0

我有一个包含汽车品牌 ID 和相关汽车型号的列表,例如:

1 卡罗拉
1 雅力士
1 矩阵
2 切诺基
2 自由
3 CR-V
3 CR-Z
3 元素
3 思域
3 飞行员

其中 1 = 丰田,2 = 吉普,3 = 本田。请注意,每个汽车品牌的车型基数不同。

我想检索每个汽车品牌的随机汽车型号。每个汽车品牌要检索的汽车数量取决于相关模型的总数和输入浮点参数:'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 
    */
    ...
}
4

1 回答 1

0

也许最简单的方法是将给定键的所有值复制到一个新容器中,例如 a vectorrandom_shuffleit 和resize()it 以将其大小减小到 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);
于 2011-03-23T13:40:19.467 回答