A hash table container in C++ STL

1、unordered_map

unordered_map is a hash table container in C++ STL, used to store key-value pairs, and supports operations such as fast lookup, insertion, and deletion. We can use unordered_map to store the correspondence between Roman numerals and integers.

Let's give a simple example to illustrate how to use this hash table container.

#include <unordered_map>
#include <iostream>
using namespace std;

int main() {
    
    
//1定义了一个 unordered_map 对象 m,并使用大括号语法添加了三个键值对。
    unordered_map<string, int> m = {
    
    
        {
    
    "one", 1},
        {
    
    "two", 2},
        {
    
    "three", 3}
    };
   //2使用 m["key"] 的方式来访问指定键的值 
    cout << m["two"] << endl;  // 输出 2
    //3m[key] = value 的方式来新增或修改一项键值对
    m["four"] = 4;  // 新增一项键值对
   //4 size() 函数可以返回 unordered_map 中键值对的总数。
    cout << m.size() << endl;  // 输出 4
    return 0;
}

There is a specific question on Likou that uses this container, and you can also try it out.
13 Roman Numerals to Integer
Below is my code:

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int romanToInt(string s) {
    
    
    unordered_map<char,int> roman_map = {
    
    
    {
    
    'I', 1},
    {
    
    'V', 5},
    {
    
    'X', 10},
    {
    
    'L', 50},
    {
    
    'C', 100},
    {
    
    'D', 500},
    {
    
    'M', 1000}
    };
    int m =roman_map[s.back()]; //最右一个数
    //遍历求和,大数相加,小数相减
    for(int i =s.length()-2;i>=0;i--){
    
    
        if(roman_map[s[i]]>=roman_map[s[i+1]]){
    
    
            m+=roman_map[s[i]];
            cout<<m<<endl;
        }
        else{
    
    
            m-=roman_map[s[i]];
            cout<<m<<endl;
        }
    }
    return m;
}  
int main(){
    
    
    string s ="MCMXCIV";
    cout<<romanToInt(s);
}

Guess you like

Origin blog.csdn.net/CSDN_Yangk/article/details/131258900