为什么我的装饰功能不起作用?

Xol*_*lve 1 c++ string

void trim(string &str)
{
    string::iterator it = str.begin();
    string::iterator end = str.end() - 1;

    // trim at the starting
    for(; it != str.end() && isspace(*it); it++)
        ;
    str.replace(str.begin(), it, "");

    // trim at the end
    for(; end >= str.begin() && isspace(*end); end--)
        ;
    str.replace(str.end(), end, ""); // i get the out_of_range exception here
}
Run Code Online (Sandbox Code Playgroud)

我想修剪一串空格.首先我从起点开始行程并且它工作正常,然后我从末尾找到空格的位置并尝试将其删除并抛出异常.

为什么?

sbi*_*sbi 7

更改字符串会使迭代器无效.解决此问题的一种方法是仅修改字符串一次.顺便说一下,这也可能更快:

void trim(std::string &str)
{
    std::string::size_type begin=0;
    while(begin<str.size() && isspace(str[begin]))
      ++begin;
    std::string::size_type end=str.size()-1;
    while(end>begin && isspace(str[end]))
      --end;
    str = str.substr(begin, end - begin + 1)
}
Run Code Online (Sandbox Code Playgroud)