c++ std::map<std::string, int> 与std::string_view一起使用

标签 c++

假设我有一个 std::map<std::string, int> .有什么办法可以使用它的at方法与 std::string_view ?这是一个代码片段:

std::string_view key{ "a" };
std::map<std::string, int> tmp;
tmp["a"] = 0;
auto result = tmp.at(key);
这是我从 clang 12.0 获得的输出

error: no matching member function for call to 'at'

auto result = tmp.at(key);

最佳答案

发生这样的事情需要三件事:

  • map 的比较器必须是透明比较器(需要 C++14,但您已经在使用 string_view,即 C++17,所以这是一个有争议的问题)。
  • at()当容器具有透明比较器时,方法必须具有参与重载决议的重载。
  • 该参数必须可转换为 map 的 key_type .

  • 在您的示例中,这些都不是真的。默认std::less比较器不是透明比较器,at() 没有这样的过载, 和 std::string没有来自 std::string_view 的隐式转换.
    您无能为力at() , 但是你可以对比较器做一些事情 namely using the (transparent std::void comparator) ,然后使用 find()而不是 at() ,它确实有一个合适的重载:
    #include <map>
    #include <string>
    #include <string_view>
    
    
    int main()
    {
        std::string_view key{ "a" };
        std::map<std::string, int, std::less<void>> tmp;
        tmp["a"] = 0;
    
        auto iter=tmp.find(key);
    }
    
    More complete demo

    关于c++ std::map<std::string, int> 与std::string_view一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66342381/

    相关文章:

    c++ - 在字符数组中输入数字

    C++矩阵计算效率

    c++ - '2D' 相机在 OpenGL/C++ 中的移动

    c++ - 如何初始化 GLfloat 数组?

    C++ 我的字节数组到 int 和 int 到字节数组转换器有什么问题?

    c++ - 了解 C++ 中的指针初始化行为

    c++ - 为什么我可以使用 const char* 作为 std::map<std::string, int> 中的键

    c++ - 如何最好地对使用 boost::asio::yield_context 的类进行单元测试?

    c++ - fatal error : FlexLexer. h:没有那个文件或目录

    c++ - C++/VS2010 中 sprintf 的奇怪行为