为什么vector总是空的?

Why does vector always stay empty?

本文关键字:vector 为什么      更新时间:2023-10-16

因此,程序将文件夹的路径作为命令行选项,然后读取文件夹中的所有文件,如果文件内容正确(应该是整数),则输出文件名和整数(例如:test.txt: 192), check()函数确定文件数据是否正确。

在所有好的文件都打印出来之后,我也想打印所有的坏文件。所以我试着在vector<string>中收集他们的名字,但不幸的是它总是空的。所有的逻辑都在print()函数中,因为程序应该使用多线程处理文件。当我不使用线程时,一切都很好。

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<iomanip>
#include<regex>
#include<boost/algorithm/algorithm.hpp>
#include<boost/range/algorithm.hpp>
#include<boost/filesystem.hpp>
#include<locale>
#include<thread>
using std::cout;
using std::endl;
using namespace boost::filesystem;
using vec = std::vector<std::string>;
static int summ = 0;
static vec vc;
inline auto check(const std::string &s)
{
    std::regex reg1("[[:blank:]]*[-[:digit:]]*[[:blank:]]*", std::regex_constants::ECMAScript);
    return regex_match(s, reg1);
}
void print(boost::filesystem::directory_entry &dir,std::vector<std::string> &v)
{
std::ifstream is;
is.open(dir.path().string());
std::stringstream buf;
buf << is.rdbuf();
auto temp = buf.str();
if(!check(temp))
{
    vt.push_back(dir.path().filename().string());
    is.clear();
    is.close();
    return;
}
cout.setf(std::ios::left, std::ios::adjustfield);
cout << std::setw(20) << dir.path().filename().string() << ": " << std::stoi(temp) << endl;
is.clear();
is.close();
}

int main(int argc, char *argv[])
{
setlocale(LC_ALL, "");
int sum{};
std::vector<std::string> vt;
std::ifstream file;
if (argc < 2)
{
    cout << "usage: prog path" << endl;
    return 1;
}
boost::filesystem::path p(argv[1]);
if (!boost::filesystem::is_directory(p))
{
    cout << "not a directory!";
    return 1;
}
for (auto &el : boost::filesystem::directory_iterator(p))
{
    if (!boost::filesystem::is_directory(el))
    {
        std::thread tr(print, el,vc);
        tr.join();
    }
}
//cout << "Sum: " << sum << endl;
cout << "Files with wrong input data: n";
boost::copy(vt, std::ostream_iterator<std::string>(cout, "n"));   //empty here
}

问题:

vt为空,因为您从未向其添加任何内容。你把vc传递给print。即使您将vt传递给print,它也不会编译,因为您在print中对不存在的变量vt调用push_back。您可能指的是v,即参数的名称。

解决方案:

  1. 去掉main
  2. 中的static vec vc;std::vector<std::string> vt;
  3. print中调用v.push_back而不是vt.push_back

:

  1. std::向量。Push_back不是线程安全的,所以如果你同时在多个线程上访问它,你应该锁定它。你没有,因为:
  2. 你实际上没有并行任何东西,因为你在启动每个线程后立即加入。
  3. 磁盘IO将成为瓶颈,所以即使你并行检查,也可能不会更快。
相关文章: