以下代码无法在最近的编译器上构建(g ++ - 5.3,clang ++ - 3.7).
#include <map>
#include <functional>
#include <experimental/string_view>
void f()
{
using namespace std;
using namespace std::experimental;
map<string, int> m;
string s = "foo";
string_view sv(s);
m.find(sv);
}
Run Code Online (Sandbox Code Playgroud)
clang返回的错误:
error: no matching member function for call to 'find'
m.find(sv);
~~^~~~
Run Code Online (Sandbox Code Playgroud)
但是不find
应该能够使用类似的类型?Cppreference提到了以下重载:
template< class K > iterator find( const K& x );
发生同样的错误boost::string_ref
.
我有一个代表DB对象的地图.我希望从中得到"众所周知"的价值观
std::map<std::string, std::string> dbo;
...
std::string val = map["foo"];
Run Code Online (Sandbox Code Playgroud)
一切都很好但是我觉得"foo"在每次通话时都被转换为临时字符串.当然,拥有一个常量的std :: string会更好(当然,与刚刚获取对象的磁盘IO相比,它可能只是一个很小的开销,但我认为它仍然是一个有效的问题).那么std :: string常量的正确习惯是什么?
例如 - 我可以
const std::string FOO = "foo";
Run Code Online (Sandbox Code Playgroud)
在hdr中,但后来我得到了多份副本
编辑:还没有回答说如何声明std :: string常量.忽略整个地图,STL等问题.很多代码都是以std :: string为导向的(我当然是这样)并且很自然地需要为它们设置常量而不需要为内存分配反复付费
EDIT2:从曼努埃尔手中接过PDF回答的二级问题,添加了一个不好习惯的例子
编辑3:答案摘要.请注意,我没有包含那些建议创建新字符串类的内容.我很失望,因为我希望有一个简单的东西只能在头文件中工作(如const char*const).无论如何
a)来自马克b
std::map<int, std::string> dict;
const int FOO_IDX = 1;
....
dict[FOO_IDX] = "foo";
....
std:string &val = dbo[dict[FOO_IDX]];
Run Code Online (Sandbox Code Playgroud)
b)来自vlad
// str.h
extern const std::string FOO;
// str.cpp
const std::string FOO = "foo";
Run Code Online (Sandbox Code Playgroud)
c)来自Roger P.
// really you cant do it
Run Code Online (Sandbox Code Playgroud)
(b)似乎与我想要的最接近,但有一个致命的缺陷.我不能拥有使用这些字符串的静态模块级代码,因为它们可能尚未构建.我想过(a)并且实际上在序列化对象时使用类似的技巧,发送索引而不是字符串,但对于通用解决方案来说似乎有很多管道.很遗憾(c)获胜,std:string 没有简单的常量
假设您有一个std::unordered_set<std::string>
.
您有一个std::string_view
要在容器中搜索的对象。问题是,您不想std::string
从您的 中创建 a std::string_view
,因为这种首先违背了使用的目的std::string_view
。
不过,好像std::string_view
应该可以作为key使用;应该有某种方式来比较std::string_view
and std::string
,因为它们基本上代表同一件事。但是没有,无论如何都没有在 STL 中。
这是一个僵局,我是否被迫编写自己的比较对象std::string_view
并std::string
与我的对象一起使用std::unordered_set
?
编辑:这个问题特定于 string_view 对象。“重复”问题不相关。正如预期的那样,我收到了一个独特问题的独特答案。