C++ 使用std::async多线程解析文件存结果到vector报错如何解决
错误原因
编译报错的核心是类型不匹配:
- 你定义的
results2是std::vector<int>类型,只能存储int类型元素 - 你尝试插入的
results是std::future<std::vector<int>>类型,编译器找不到两种类型的转换规则,因此触发报错。
实现逻辑调整
按照你原定的「先提交所有异步任务,再统一收集结果」的设计,调整逻辑如下:
- 新增一个专门存储future的容器,存放所有异步任务的返回句柄
- 所有任务提交完成后,遍历future容器,逐个调用
.get()方法等待任务执行完成,拿到每个任务返回的std::vector<int>结果 - 将每个返回的vector内的元素,追加到最终的结果集合中
修改后可运行代码
#include <vector> #include <iostream> #include <future> #include <string> // 原代码遗漏std::string对应的头文件,此处补充 std::vector<int> parsefilefunction(std::string filepath) { // 此处保留你原有的解析逻辑示例 std::vector<int> vec{1, 2, 3}; return vec; } std::vector<std::string> s = { "file1.json", "file2.json", "file3.json", "file4.json", "file5.json" }; int main() { // 存储所有异步任务的future句柄 std::vector<std::future<std::vector<int>>> task_futures; for (size_t i = 0; i < s.size(); i++) { task_futures.emplace_back(std::async(std::launch::async, parsefilefunction, s[i])); } // 统一收集所有结果 std::vector<int> results2; for (auto& fut : task_futures) { auto single_result = fut.get(); results2.insert(results2.end(), single_result.begin(), single_result.end()); } // 测试输出验证结果,可按需删除 for (int num : results2) { std::cout << num << " "; } return 0; }
编译使用你原有命令即可:c++ stackoverflow.cpp -std=c++14 -pthread
内容的提问来源于stack exchange,提问作者schlumpel
相关产品推荐
相关产品推荐

