Get the last element of a std::string

后端 未结 4 1005
自闭症患者
自闭症患者 2020-12-08 03:38

I was wondering if there\'s an abbreviation or a more elegant way of getting the last character of a string like in:

char lastChar = myString.at( myString.le         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 04:24

    You could write a function template back that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

    template 
    typename C::reference back(C& container)
    {
        return container.back();
    }
    
    template 
    typename C::const_reference back(const C& container)
    {
        return container.back();
    }
    
    char& back(std::string& str)
    {
        return *(str.end() - 1);
    }
    
    char back(const std::string& str)
    {
        return *(str.end() - 1);
    }
    

    Then you can just say back(foo) without worrying whether foo is a string or a vector.

提交回复
热议问题