C++ 迭代向量以更新word_计数器
我有一个结果结构向量,每个结果结构都包含一个合同字符串,它是一个“单词” 我想找出向量中不同单词的出现频率 我可以使用分隔符将它们连接成一段文本,并从中提取频率C++ 迭代向量以更新word_计数器,c++,vector,iterator,boost-multi-index,C++,Vector,Iterator,Boost Multi Index,我有一个结果结构向量,每个结果结构都包含一个合同字符串,它是一个“单词” 我想找出向量中不同单词的出现频率 我可以使用分隔符将它们连接成一段文本,并从中提取频率 text_tokenizer tok(text, separator); for (text_tokenizer::iterator it = tok.begin(), it_end = tok.end(); it != it_end; ++it) { ++total_occurrences; word_cou
text_tokenizer tok(text, separator);
for (text_tokenizer::iterator it = tok.begin(), it_end = tok.end();
it != it_end; ++it)
{
++total_occurrences;
word_counter::iterator wit = wc.insert(*it).first;
wc.modify_key(wit, ++bl::_1);
}
使用多索引容器
typedef multi_index_container
<
word_counter_entry,
indexed_by
<
ordered_non_unique
<
BOOST_MULTI_INDEX_MEMBER(
word_counter_entry, unsigned int, occurrences),
std::greater<unsigned int>
>,
hashed_unique
<
BOOST_MULTI_INDEX_MEMBER(word_counter_entry, std::string, word)
>
>
> word_counter;
typedef多索引容器
<
word\u计数器\u条目,
索引
<
有序非唯一
<
增强多索引成员(
字计数器输入,无符号整数,出现次数),
标准::更大
>,
哈希_唯一
<
BOOST\u多索引\u成员(word\u计数器\u条目,标准::字符串,word)
>
>
>字计数器;
但在原始向量上迭代似乎更干净
for (std::vector<Result>::iterator it = begin(v); it != end(v); ++it)
{
//Magically update word counter
}
for(std::vector::iterator it=begin(v);it!=end(v);+it)
{
//神奇地更新字计数器
}
非常感谢任何合适的魔法。您只需创建一个地图,以单词为键,以频率(计数)为值
std::map<std::string, int> frequency;
for (auto& result : v) {
frequency[result.contract]++;
}
std::map频率;
用于(自动和结果:v){
频率[结果.合同]+;
}
的确如此。我试图使用Boost功能,避免使用自定义代码,但您的建议要简单得多!
std::map<std::string, int> frequency;
for (auto& result : v) {
frequency[result.contract]++;
}