如果我std::reverse在std::string变量上使用,我可以安全地假设空字符'\0'将放在字符串的开头吗?
Die*_*Epp 15
不,它不包含NUL字节(除非你把它放在那里).前向迭代器也不包含NUL字节,它只会遍历字符串本身的字符.
但是,保证NUL字节超过.c_str()或结束.data().
#include <string>
#include <iostream>
#include <algorithm>
int main() {
std::string s = "Hello";
std::cout << "Forwards:\n";
for (auto i = std::begin(s), e = std::end(s); i != e; ++i) {
std::cout << *i << ' ' << static_cast<int>(*i) << '\n';
}
std::cout << "Backwards:\n";
std::reverse(std::begin(s), std::end(s));
for (auto i = std::begin(s), e = std::end(s); i != e; ++i) {
std::cout << *i << ' ' << static_cast<int>(*i) << '\n';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Forwards: H 72 e 101 l 108 l 108 o 111 Backwards: o 111 l 108 l 108 e 101 H 72
| 归档时间: |
|
| 查看次数: |
500 次 |
| 最近记录: |