Text manipulation is a huge topic. std::string doesn’t cover all of it.
This section primarily tries to clarify std::string’s relation to char*, zstring, string_view, and gsl::span<char>.
The important issue of non-ASCII character sets and encodings (e.g., wchar_t, Unicode, and UTF-8) will be covered elsewhere.
SL.str.1: Use std::string to own character sequences
SL.str.2: Use std::string_view or gsl::span<char> to refer to character sequences
SL.str.3: Use zstring or czstring to refer to a C-style, zero-terminated, sequence of characters
SL.str.4: Use char* to refer to a single character
SL.str.5: Use std::byte to refer to byte values that do not necessarily represent characters
SL.str.10: Use std::string when you need to perform locale-sensitive string operations
SL.str.11: Use gsl::span<char> rather than std::string_view when you need to mutate a string
SL.str.12: Use the s suffix for string literals meant to be standard-library strings
那么,究竟啥场景能用 std::string_view 类型参数?
F.25: Use a zstring or a not_null<zstring> to designate a C-style string 节有一句话:
If you don’t need null termination, use string_view.
intmain(){ std::vector<int> c = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (constauto& e : c) { std::cout << e << ' '; } std::cout << '\n';
for (auto iter = c.begin(); iter != c.end();) { if (2 == *iter || 3 == *iter) { // remove 2 and 3 // iter = c.erase(iter); // This is correct in all cases
c.erase(iter++); // for vector, this is incorrect! } else { ++iter; } }
for (constauto& e : c) { std::cout << e << ' '; } std::cout << '\n'; }