當我使用一個基于范圍的for回圈在一個臨時的std::string(rvalue?)上回圈時,似乎有一個額外的字符,即null terminator 。
當字串不是臨時的(lvalue代替?),沒有額外的字符。為什么?
std::map<char, int> m;
for (char c : "bar") m[c] =0;
for (auto [c, f] : m) {
if (c == '') std::cout << "this is a null char, backward slash zero" < < std::endl;
std::cout << c << std::endl;
}
輸出:
this是一個空的char,反斜線0
a
b
r
(注意空行,在這里列印的是)
相比之下:
std::map<char,int> m;
std::string s = "bar"。
for (char c : s) m[c] = 0;
for (auto [c, f] : m) {
if (c == '') std::cout << "this is a null char, backward slash zero" < < std::endl;
std::cout << c << std::endl;
}
輸出:
a
b
r
uj5u.com熱心網友回復:
因為"bar"不是一個std::string,而是一個char陣列(const char[4]),包含4個元素,包括最后的空字符。即c-style string literal:
空字符(
'',L'',char16_t(), 等等)總是被附加到字串字面。因此,一個字串字頭"Hello"是一個const char[6],持有'H','e','l','l','o', 和''。
對于臨時的std::strings,它將如你所期望的那樣作業,即不包含空字符。
for (char c : std::string{"bar"}) m[c] = 0;
或者
using namespace std::string_literals。
for (char c : "bar"s) m[c] =0;
BTW正如@HolyBlackCat建議的那樣,你也可以使用std::string_view(自C 17以來),當從c風格的字串字面構造時,它不會包括空尾的字符。例如:
for (char c : std::string_view{"bar"}) m[c] =0;
或者
using namespace std::literals。
for (char c : "bar"sv) m[c] =0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307877.html
標籤:
上一篇:關于Double、String和Integer轉換的問題
下一篇:Python提取特定子串
