gpt4 book ai didi

c++ - 从 map-C++ 中检索字符串时出现逻辑错误

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

我可以运行该程序,但没有任何显示..如果我替换 .find("1"),我会收到编译器错误,因为 const char 不能更改为 const int。如果我用 .find('1') 替换,那么我得到的输出是“字符串不在 map 中”。我需要检索键值为 1 的字符串。我应该如何修改我的程序以获得所需的结果。

#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
typedef map<int,string> EventTypeMap;
EventTypeMap EventType;

EventType[1]="beata";
EventType[2]="jane";
EventType[3]="declan";

if(EventType.find(1)==EventType.end())
{
cout<<"string is not in the map!"<<endl;
}

return 0;
}

最佳答案

老实说,我看不出你的问题。您的键类型是 int,因此在 find() 方法中,您应该将这个确切的 int 作为键。您问题中给出的代码可以。

如果在您发布的这段代码中没有显示任何内容,那是因为您的 map 中确实有键 (int)1。要显示分配给该键的值,您可以这样写:

cout << EventType.find(1)->second << endl;

编辑 仍然不知道您的问题是什么,是否真的是个问题。这是必须工作的代码——在 GCC 和 Visual C++ 2008 上测试:

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
typedef map<int, string> EventTypeMap;
EventTypeMap EventType;

EventType[1] = "beata";
EventType[2] = "jane";
EventType[3] = "declan";

int idx = 1;
if (EventType.find(idx) == EventType.end())
cout << "string is not in the map!" << endl;
else
cout << EventType.find(idx)->second << endl;

cin.get();
return 0;
}

关于c++ - 从 map-C++ 中检索字符串时出现逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769886/

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