如何使用实验性 C++ 2017 库将文件名扩展存储到地图中

How to store a file name ext into a map using the experimental c++ 2017 lib

所以我有一个简单的小程序,我想将文件扩展名存储到地图中。当我尝试将 d->path().extension(); 存储到我的地图 data.insert(d->path().extension(),15); 时出现错误。 15 只是一个占位符,现在我想将文件分机存储为密钥。我认为错误是 std::experimental::filesystem 未知的字符串。

这是它抛出的当前错误: "std::map<_Kty, _Ty, _Pr, _Alloc>::insert [with _Kty=std::string, _Ty=int, _Pr=std::less, _Alloc=std::allocator>]" 匹配参数列表

#include <map>
#include <regex>
#include <locale>
#include <iostream>
#include <fstream>
using namespace std;
#include <filesystem>
using namespace std::experimental::filesystem;
map<string,int> rscan2(path const& f,map<string, int> const& data, unsigned i = 0)
{
    //string indet(i, ' ');

    for (recursive_directory_iterator d(f), e; d != e; ++d)
    {
    data.insert(d->path().extension(),15);
        if (is_directory(d->status()))
            rscan2(d->path(), data, i + 1);
    }
    return data;
}

int main(int argc, char *argv[])
{
    map<string, int> holdTheInfo;
    rscan2(".", holdTheInfo);
}

path 有许多转换为字符串的辅助方法。列举几个:

但实际问题是 std::map::insert 不接收键和值作为参数,仅接收值。所以你应该改用 insert_or_assign (C++17 起):

data.insert_or_assign(d->path().extension(), 15);

并且将为返回的路径调用 operator string_type(),将其转换为实际的字符串。