不理解std::filesystem::directory_iterator用法,无法将遍历条目存入vector求助
核心概念澄清
entry的类型:遍历std::filesystem::directory_iterator得到的每个entry都是std::filesystem::directory_entry类型的常量引用,本身不是字符串,你无法直接把它当做字符串类型处理。- 无法存入vector的核心原因:
entry.path()返回的是std::filesystem::path类的实例,不是原生的std::string类型,你直接把它赋值给std::string变量会触发类型不匹配的编译错误,和参数是不是常量没有关系。你看到的push_back不接收常量参数的提示属于编译器的误导性报错,根本原因是传入参数类型和vector存储的string类型不匹配,编译器找不到对应的重载函数才抛出了无关报错。
代码修正点
你写的代码需要调整几个问题:
- 补充必要的头文件与命名空间声明:使用文件系统库需要引入
<filesystem>头,同时string、vector、filesystem都属于std命名空间,需要加前缀或者使用别名简化写法。 - 正确将path转为string:调用path类的
string()方法即可转为普通字符串,如果路径包含中文可以用u8string()避免编码错误。 - 修正函数返回值逻辑:你声明了auto返回类型但没有返回对应的vector,需要明确返回类型并补充return语句。
修正后的可用代码
#include <vector> #include <string> #include <filesystem> namespace fs = std::filesystem; // 简化命名空间写法 std::vector<std::string> filepath() { std::vector<std::string> lis; std::string path = "C:/Users/Derek Comeau/3D Objects"; for (const auto& entry : fs::directory_iterator(path)) { // 调用path的string()方法转为std::string类型 std::string paths = entry.path().string(); lis.push_back(paths); } return lis; }
内容的提问来源于stack exchange,提问作者umfan110
相关产品推荐
相关产品推荐

