可以轻松地从
这是我尝试过的代码:https://gcc.godbolt.org/z/xrodd8PMq
std::string
创建std::string_view
。但如果想要使用std::string
的迭代器创建std::string
范围的字符串视图,则不起作用。这是我尝试过的代码:https://gcc.godbolt.org/z/xrodd8PMq
#include <iostream>
#include <string>
#include <string_view>
#include <iterator>
int main()
{
std::string str{"My String"};
std::string_view strView{str}; // works
//std::string_view strSubView{str.begin(), str.begin() + 2}; // error
}
当然,我们可以从str
中提取子字符串并使用它来创建一个字符视图strSubView
,但这会额外创建一个字符串。
我发现std::basic_string_view
的第五个构造函数接受迭代器范围。
template<class It, class End>
constexpr basic_string_view(It first, End last);
这只涉及到std::string
的迭代器还是只有std::basic_string_view
本身?如果不是因为std::string
的迭代器,那么我们为什么不应该拥有一个呢?毕竟字符串视图:
描述了一个可以引用连续的字符对象序列的对象!
考虑到连续的字符序列的范围,难道我们不应该计数吗?
std::string_view
也可以创建子串,例如:strSubView = strView.substr(0, 2);
。这与您尝试的操作相似。 - Drew Dormann