gpt4 book ai didi

c++ - 如何在映射中插入值以列表对?

转载 作者:行者123 更新时间:2023-11-30 02:48:17 25 4
gpt4 key购买 nike

我的容器是这样的:

map<DWORD, list<pair<string,LARGE_INTEGER>>> map_to_list_items;

此代码编译失败:

map<DWORD, list<pair<string,LARGE_INTEGER>>>::iterator iter_map_to_list_items = map_list_items.find(dwThreadID);
if ( iter_map_to_list_items == map_to_list_items.end() )
{
map_to_list_itens.insert ( pair<DWORD,pair<string,LARGE_INTEGER>>(dwTheadID, (string("Start"), m_TimePRE)));
}

最佳答案

我的理解是你有两个像这样的变量:

map<DWORD, list<pair<string, LARGE_INTEGER>>> map_to_list_items;
map<DWORD, list<pair<string, LARGE_INTEGER>>> map_list_tempos_threads;

要简化代码,您可以做的第一件事就是使用新的 C++11 的 auto关键字,而不是显式键入整个繁琐的迭代器名称:

auto it = map_list_tempos_threads.find(dwThreadID);

(请注意,您的代码中可能有一些拼写错误,因为您使用的是 dwTheadID 而不是 dwThreadID..._itens 而不是 ..._items)。

然后,您可以简单地使用 std::map::operator[]重载以在 map 中插入新项目(如果不存在):

if (it == map_to_list_items.end())
{
//
// Insert the new list<pair<string, LARGE_INTEGER>> in the map,
// assuming:
// - key: dwThreadID
// - string: "Start"
// - LARGE_INTEGER: m_TimePRE
//

list<pair<string, LARGE_INTEGER>> l;
string s = "Start";
l.push_back(make_pair(s, m_TimePRE)) // I'm assuming m_TimePRE is a LARGE_INTEGER
map_to_list_items[dwThreadID] = move(l); // Move the list into the map
}

编辑:

这是一个更短的插入代码版本:

map_to_list_items[dwThreadID].emplace_back("Start", m_TimePRE);

关键是,如果dwThreadID (“键”)在 map 中,默认构造的“值”(即list<pair<string, LARGE_INTEGER>>)在 map 由 operator[]重载,并返回对它的引用。
然后,list::emplace_back()在该引用上被调用,新的 ("Start", m_TimePRE)对被添加到(之前为空,因为默认构造)列表中。

有了这个表单,输入的内容就少了很多,但是有几个操作是“在幕后”发生的;相反,在第一种形式中,代码及其逻辑步骤更加明确。

关于c++ - 如何在映射中插入值以列表对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22103568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com