首页 > 解决方案 > 如何根据用户输入将对插入到地图中,然后找到与用户给定的键关联的元素?

问题描述

如果我添加部分以查找元素,则以下代码不起作用。没有那部分,代码的第一部分正在添加和显示元素stl::map

    #include<iostream>
    #include<map>
    #include<utility>

    using namespace std;

    int main()
    {
        int n, k, q;
        char *v;
        map<int, char*> m1;
        map<int, char*>::iterator it;
        cout << "enter number of elements\n";
        cin >> n;
        cout << "enter number and string- \n";
        for(int i=0; i<n; i++)
        {
            cin >> k;
            cin >> v;
            m1.insert(pair<int, char*>(k, v));
        }
        cout << "elements are- " << endl;
        for (it=m1.begin(); it!=m1.end(); it++)
            cout << it->first << " " << it->second << "\n";

    /* if the code is kept up to this and compiled,
       the map elements are displayed. If the following code is added
       to find the element, the application crashes just after taking
       an input to fill the map */

        cout << "enter a key to find element\n";
        cin >> q;
        it = m1.find(q);
        if(it!=m1.end())
        cout << it->first << " " << it->second ;
        else
            cout << "key was not found\n";

        return 0;
    }

标签: c++stl

解决方案


将 更改char*string。是char*一个悬空指针。它不引用分配的缓冲区。更改为 astring将动态处理所有细节。

更改m1.insert(pair<int, char*>(k, v));m1[k] = v;。后一种修改和访问映射的方式是使用映射的原因之一:为了语法上的方便。第一种方式没有什么“错误”,但它更打字而且不太清楚。


推荐阅读