c++ - 找到一种方法将匹配的键和值从映射推回向量
问题描述
我在 Java 中有与此类似的代码,但让它在 C++ 中工作是另一回事。目前,此功能确实正确找到了密钥并将密钥推到我的向量后面。我想抓住键和它的一对值都被插入到向量的同一个索引中。我已经研究过使用一对作为我的向量,所以它会是(键,一对值),我不确定我是否能够做到。
vector<string> getIfPresentPartOfSpeech(multimap<string, pair<string, string>> dictionary, string name) {
vector<string> response;
auto it = dictionary.begin();
while (it != dictionary.end()) {
// Check if value of this entry matches with given value
if (it->second.first == name) {
// Yes found
// Push the key in given map
response.push_back(it->first);
}
// Go to next entry in map
it++;
}
return response;
}
解决方案
为您定义一个结构response
并返回std::vector
该类型的一个。
struct Response {
std::string key;
std::pair<std::string, std::string> resp_pair;
};
vector<Response> getIfPresentPartOfSpeech(multimap<string, pair<string, string>> dictionary, string name) {
vector<Response> response;
auto it = dictionary.begin();
while (it != dictionary.end()) {
// Check if value of this entry matches with given value
if (it->second.first == name) {
// Yes found
// Create a Response object
Response resp;
resp.key = it->first;
resp.resp_pair = it->second;
// Push it in the vector
response.push_back(resp);
}
// Go to next entry in map
it++;
}
return response;
}
通过使用emplace_back
而不是push_back
避免容器元素的多个副本传递来进一步优化这一点是可能的。
推荐阅读
- html - 中心 div 具有高于视口高度的未知高度
- html - 移动设备页面右侧的空白区域
- javascript - 从输入字段验证 onchange 文件名(纯 javascript)
- css - Transform.scale() 不缩放给定的空间
- social-tables - 通过 ST Developer Portal 的 API 控制台创建事件
- c# - 无法让物体发生碰撞
- c# - 检查打包的 WPF 应用程序是随启动还是手动运行?
- javascript - 正确渲染图像 Blob
- ruby-on-rails - Ruby on Rails 4:有效吗?总是返回真
- javascript - 监控和报告读取 Popover 的累积运行时间