简体   繁体   English

如何将迭代结果添加到 c++ 中的新多图?

[英]How to add the results from the iteration to new multimap in c++?

How to insert result into a new multimap??如何将结果插入新的多图? I am trying to search over dictionary container to find keyword given by the user and I need to iterate over the tempCollector to find distinct elements.我正在尝试搜索字典容器以查找用户给出的关键字,并且我需要遍历 tempCollector 以查找不同的元素。 But, I can't seem to find a way to store the results in tempCollector.但是,我似乎找不到将结果存储在 tempCollector 中的方法。

//current container with all the data
multimap<string, DictionaryItem> dictionaryContainer;
void search(vector<string> input) {
    if (dictionaryContainer.empty()) {
        cout << "it's empty";
    }
    int inputSize = input.size();
    string tempKeyword = input[0];
    //need to copy or insert the value and keys to the tempCollector
    multimap<string, DictionaryItem>tempCollector;       
    //iteration to find keyword; want to store the result in tempCollector
    auto its = dictionaryContainer.equal_range(tempKeyword);
    for (multimap<string, DictionaryItem>::iterator itr =its.first; itr != its.second; itr++) {
        itr->second.print();          
    }
};

If you want to copy the whole its range:如果要复制its范围:

tempCollector.insert(its.first, its.second);

If you want to copy each element:如果要复制每个元素:

for (auto itr =its.first; itr != its.second; itr++) {
    if (condition) {
        tempCollector.emplace(tempKeyword, itr->second);
        //or
        tempCollector.insert(*itr);
        //or
        tempCollector.emplace(tempKeyWord, DictionaryItem(...));
    }
}

Keep in mind (multi)map handles pairs of key/values as std::pair<Key,T> (aka value_type ).请记住(多)映射将键/值对处理为std::pair<Key,T> (又名value_type )。
The multimap::insert method assumes you've already constructed the pair(s) to insert, while multimap::emplace will build them for you. multimap::insert方法假定您已经构建了要插入的对,而multimap::emplace将为您构建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM