简体   繁体   English

c++ 中的 back() 的目的是什么?

[英]What is the purpose of back() in c++?

Here is the code:这是代码:

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> list = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        int total = list[s.back()];
        for(int i = s.length() - 2; i>=0; --i){
            if(list[s[i]] < list[s[i+1]]){
                total -= list[s[i]];
            }
            else{
                total += list[s[i]];
            }
        }
        return total;
    }
};

I can't understand what is the purpose of this line:我不明白这条线的目的是什么:

int total = list[s.back()];

can anyone tell me what is the purpose of谁能告诉我的目的是什么

"back()" “背部()”

in the above code?在上面的代码中?

As I have understood the string s contains a number using Roman numerals as for example "IV" that represents 4. So the expression s.back() yields the last symbol in the string that is 'V' .据我了解,字符串 s 包含一个使用罗马数字的数字,例如表示 4 的"IV" 。因此表达式 s.back() 产生字符串中的最后一个符号'V'

That is the string is traversed from right to left.也就是从右到左遍历字符串。

In other words, for sequential containers with rare exceptions the member function front yields the first element of the container and the function back yields the last element of the container.换句话说,对于具有罕见异常的顺序容器,成员 function front产生容器的第一个元素,而 function back产生容器的最后一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM