如果我在 std::string
变量上使用 std::reverse
,我可以安全地假设空字符 '\0'
会放在字符串的开头吗?
最佳答案
不,它不会包含 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;
}
输出:
Forwards: H 72 e 101 l 108 l 108 o 111 Backwards: o 111 l 108 l 108 e 101 H 72
关于C++14 - std::revers(ed) std::string 是否在开头包含空字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32509637/