微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

如何将结果插入到新的多重映射中??我正在尝试搜索字典容器以查找用户给出的关键字,我需要遍历 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();          
    }
};

解决方法

如果您想复制整个 its 范围:

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

如果要复制每个元素:

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(...));
    }
}

请记住(多)映射将键/值对处理为 std::pair<Key,T>(又名 value_type)。
multimap::insert 方法假定您已经构建了要插入的对,而 multimap::emplace 将为您构建它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。