64,651
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<vector>
#include<filesystem>
#include<regex>
#include<map>
#include<vector>
using namespace std;
using namespace std::filesystem;
template<typename _M>
map<string, vector<string>> divide(const path& path,_M method) { //path为目录路径,method为划分方式,通过返回一个string进行分类
if (!exists(path))
return {};
directory_entry entry(path); //文件入口
directory_iterator list(entry);
map<string, vector<string>> fileSet;
for (auto& file : list) {
fileSet[method(file.path().filename().string())].push_back(file.path().string());
}
return fileSet;
}
int main() {
regex re("\\w_(\\w+)_\\d+\.dat"); //匹配模式,且把第二串字符作为分类依据
auto result = divide("C:/project/",
[&re](const string& filename)->string {
smatch match; //存储匹配结果
auto i = regex_match(filename, match, re);
return match[1].str();
});
for (auto& type : result) { //显示一下
cout << type.first << ":" << endl;
for (auto& file : type.second) {
cout << " " << file << endl;
}
}
return 0;
}