gpt4 book ai didi

c++ - int 和元组的静态 STL 映射返回 0

转载 作者:行者123 更新时间:2023-11-28 05:12:56 28 4
gpt4 key购买 nike

为我的 C++ 类(class)构建日历。我有一个静态方法和静态容器的实用程序类。最值得注意的是:

字典.h

static std::map<int,std::tuple<std::string,int>>months;
static std::map<int,std::tuple<std::string,int>>::iterator mitr;

此映射包含 0-11 月份作为键。元组值包含每个月的字符串表示和每个月的天数。例如:

字典.cpp

map<int,tuple<string,int>> Dictionary::initMonths(){
map<int,tuple<string,int>>m;
map<int,tuple<string,int>>::iterator mapitr = m.begin();
m.insert(mapitr, make_pair(0,make_tuple("January",31)));
m.insert(mapitr, make_pair(1,make_tuple("February",28)));
// insert remaining months...
return m;
}

当我尝试从另一个类访问此 map 时出现问题:

日历.cpp

Calendar::Calendar(){
Dictionary::init();
time_t t = chrono::system_clock::to_time_t(chrono::system_clock::now());
tm* t2 = localtime(&t);
int mo = (t2->tm_mon);
Dictionary::mitr = Dictionary::months.find(mo);
cout<<(*Dictionary::mitr).first<<endl; // => 0
cout<<get<0>((*Dictionary::mitr).second)<<endl; // nothing
}

我不确定我在这里做错了什么。任何建议,将不胜感激。

编辑:

void Dictionary::init(){
packaged_task<map<int,tuple<string,int>>()>task3(initMonths);
future<map<int,tuple<string,int>>>fu3 = task3.get_future();
guarded_thread t3(std::move(task3));
map<int,tuple<string,int>>months = fu3.get();
}

最佳答案

你究竟是如何初始化 map 的?您的字典代码显示了一个函数 Dictionary::initMonths(),它返回一个映射,但是您的示例应用程序代码只是调用了 Dictionary::init()。如果这些函数实际上是相同的,而这只是一个拼写错误,那么您就忘记了将 initMonths 的返回值分配给静态 months 变量。

就像一个建议,在这里有一个 map 似乎真的有点矫枉过正——在这种情况下,你实际上不想要 map 的属性,它在树状结构中排列稀疏键。仅使用 vector 或固定数组并仅通过索引访问而不使用迭代器等可能更容易(并且更快,值得)。

关于c++ - int 和元组的静态 STL 映射返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43175465/

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