【问题标题】:print the unordered map values when key value is given as input当键值作为输入时打印无序映射值
【发布时间】:2022-05-11 14:36:34
【问题描述】:

我已经编写了代码来读取字符串值并映射为键和值。现在我在打印值时遇到问题,如果我们将键值作为无序映射的输入。 下面是代码。 例如,如果我们选择 1 作为选项,键是服务器,输出应该是“IN-OLDEB-1”作为值。

文件中的数据如下:

[Server]
IN-OLDEB-1;
[Location]
\\IN-kkkk\PP620DAT;
[ServerAppName]
OPOPAPP;
[DBShareName]
PP620DAT;
[Commits]
10;
[DeTablePath]
\\CDM\DRGdddTBL;

#include "stdafx.h"

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>

using namespace std;

int main()

{

    ifstream myfile;

    myfile.open("Wconfig.sys");
unordered_map <string, string> database;
    string tag, value;
    if (myfile.is_open())

{
    while (!myfile.eof())
    {

        getline(myfile, tag);
        getline(myfile, value);
        value.pop_back();
        database[tag.substr(1, tag.size() - 2)] = value;
        //database[tag] = value;
        //cout << database["ServerName"] << endl;
    }


string tag_array[] = {
        "Server",
        "Location",
        "ServerAppName",
        "DBShareName",
        "Commits",
        "DeTablePath"};

cout << "Enter your option: " << endl
        << "1 - Server" << endl
        << "2 - Location" << endl
        << "3 - ServerAppName" << endl
        << "4 - DBShareName" << endl
        << "5 - Commits" << endl
        << "6 - DeTablePath" << endl;


int n;
while (cin >> n) 
{
    cout << n << endl;
    if (n >= 1 && n <= 6)
        cout << endl << database[tag_array[n - 1]] <<endl;
    else
        cout << endl << "Enter Valid Input" << endl;
}
return 0;
}

【问题讨论】:

标签: c++ c++11 visual-c++


【解决方案1】:

有几种选择:

如果unordered_map_name 是映射,"specific string" 是您要打印的键:

1:cout &lt;&lt; unordered_map_name.at("specific string") &lt;&lt; endl;

2:cout &lt;&lt; unordered_map_name["specific string"] &lt;&lt; endl;

3:cout &lt;&lt; unordered_map_name.find("specific string")-&gt;second &lt;&lt; endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2021-09-18
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    相关资源
    最近更新 更多