修剪空白/转换迭代器
我想编写两个单行函数,它们将修剪字符串左侧和右侧的空格。左侧没有问题:
void trimLeft(string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), (int (*)(int))isgraph));
}
但是当我尝试右侧类似的操作时:
void trimRight(string &s) {
s.erase(find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph), s.end());
}
我遇到了一些编译器错误。问题是我必须将reverse_iterator(由find_if返回)转换为普通迭代器。如何做到这一点?
I wanted to write two one-line functions which will trim white spaces from left and right side of a string. Left side weren't problem:
void trimLeft(string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), (int (*)(int))isgraph));
}
But when I tried something similar for right side:
void trimRight(string &s) {
s.erase(find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph), s.end());
}
I had some compiler errors. The problem is that I must convert reverse_iterator (which is returned by find_if) to normal iterator. How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
base()
成员函数从其reverse_iterator恢复底层迭代器。You can use the
base()
member function to recover the underlying iterator from its reverse_iterator.查看文档,似乎 string::erase 应该采用reverse_iterators 就可以了。问题是您混合了反向和正向迭代器。所以尝试
编辑:不。
Looking at the documentation, it seems like string::erase should take reverse_iterators just fine. The problem is that you're mixing reverse and forward iterators. So try
Edit: Nope.
使用 boost::trim 吗?
http://www.boost.org/doc /libs/1_47_0/doc/html/string_algo/usage.html#id2895820
Use boost::trim?
http://www.boost.org/doc/libs/1_47_0/doc/html/string_algo/usage.html#id2895820