如何使用 std::map 将字符串向量更改为另一个字符向量?

问题描述 投票:0回答:1

我正在尝试制作一个解码器,您可以在其中输入包含北约语音字母表的单词,并让它最终吐出翻译后的句子,只是没有制作实际的“切换器”。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

int main() {
    map<char, string> NATOMap = { {' ',"-"}, {'a', "alfa"}, {'b', "bravo"}, {'c', "charlie"}, {'d', "delta"}, {'e', "echo"}, {'f', "foxtrot"}, {'g',"golf"}, {'h',"hotel"}, {'i',"india"}, {'j', "juliett"}, {'k', "kilo"}, {'l', "lima"}, {'m',"mike"}, {'n', "november"}, {'o', "oscar"}, {'p', "papa"}, {'q',"quebec"}, {'r', "romeo"}, {'s',"sierra"}, {'t', "tango"}, {'u', "uniform"}, {'v',"victor"}, {'w',"whiskey"}, {'x',"xray"}, {'y',"yankee"}, {'z', "zulu"} };
    
    //this input comes from a file, placed here for easier testing
    string Dinpustring = "hotel echo lima lima oscar - whiskey oscar romeo lima delta";
    
    //split text
    string temp;
    stringstream ss(Dinpustring);
    vector<string> inputDxt;
    while (getline(ss, temp, ' ')) {
        inputDxt.push_back(temp);
    }
    //spit out text (testing purpouses)
    cout << "text get:\n";
    for (int i = 0; i < inputDxt.size(); i++) {
        cout << inputDxt[i] << endl;
    }
    
    //switcher(probably contains loops)??
    
    
    //not necessary for here, only to show where its supposed to end up
        fstream Doutfile3;
    Doutfile3.open("Dencoded.txt", ios::out, ios::trunc);
    if (outfile3.is_open()) {
        outfile3 << outputDxt;
    }
    outfile3.close();
    return 0;
}

我以前没有使用过地图,我对向量也不太熟悉,所以我不知道至少从哪里开始,其余的代码我已经测试过并且知道可以工作。

c++ stdvector stdmap decoder
1个回答
0
投票

A

std::map
是一种数据结构,它设置两个事物之间的关系:键和值。在您的示例中,键为
'a'
'b'
等。这些键的相应值分别为
'alfa'
'bravo'
等。

要获取与键关联的值,您应该执行以下操作:

NATOMap['a']
(将返回
'alfa'
)。

在您的情况下,您需要逆映射,即:给定一个值,获取关联的键。如果这确实是您需要做的全部,我建议反转您的地图并将其定义为:

{ {'alfa', 'a'}, {'bravo', 'b' }
等。 然后,您可以执行:
NATOMap['alfa']
来获得
'a'

© www.soinside.com 2019 - 2024. All rights reserved.