Home > front end >  What is the purpose of back() in c ?
What is the purpose of back() in c ?

Time:02-03

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?

CodePudding user response:

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'.

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.

  •  Tags:  
  • Related