c ++ vector bad access

Ben*_*tzi 0 c++ exc-bad-access vector

嗨,我有以下c ++程序:

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <boost/foreach.hpp>
#include <stdexcept>
#include <boost/flyweight.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

struct entry
{
int file;
std::vector<double> a;
};


void my_file(const std::string&file, std::vector<entry> &data, int i){
try{
    std::ifstream in(file.c_str());
    entry e;
    std::string line;
    e.file = i;
    while(getline(in,line)){
        try{
            data[i].a.push_back( boost::lexical_cast<double> (line));
        }catch(boost::bad_lexical_cast bad){
            //std::cerr << bad.what() << std::endl;
        }
    }
}catch(std::runtime_error err){
    std::cerr << err.what() << std::endl;
}

}

void write_file(const std::string &file,std::vector<entry> data,const char* t_path){
try{
    std::string new_file = t_path ;
    new_file = new_file + "/" + file;
    std::ofstream f(new_file.c_str());

    for(size_t i = 0 ;i < data[1].a.size();i++){
        std::cout << "i: " << i;
        for(size_t j = 1; j < data.size();j++){
            std::cout << "j: " << j << std::endl;
            f << data[j].a[i]<< "\t";
        }
        f << "\n";
    }

}catch(std::runtime_error err){
    std::cerr << err.what()<< std::endl;
}
}


int collect_peak(const char*argv,const char*out){
std::cout << "collecting peaks\n";
std::stringstream sstr(argv);
std::string _line;
int c = 0;
std::vector<std::string> files;

while (getline(sstr,_line)){
    std::cout << _line << std::endl;
    fs::path p(_line);
    std::string tmp = p.parent_path().string() +"/_peak_" +      p.filename().string();
    files.push_back(tmp);
    c++;
}

std::cout << "c: " << c << std::endl;
std::vector<entry> data;
for (int i=0 ; i < files.size() ;++i){
    std::cout << files[i] <<std::endl;
    my_file(files[i],data,i);
}
write_file("__peak.txt",data,out);
return 0;

}
Run Code Online (Sandbox Code Playgroud)

不知怎的,它总是在my_file方法中给我一个糟糕的访问权限.该计划实际上应该如下:

  1. 读取包含标题的多个文件和由换行符分隔的十个双精度数
  2. 将所有内容输出到一个文件中,如下所示:

    1. file\t 2. file\t 3. file\t ...

    2. file\t 2. file\t 3. file\t ...

    3. file\t 2. file\t 3. file\t ...

    4. file\t 2. file\t 3. file\t ...

    5. file\t 2. file\t 3. file\t ...

这实际上已经有效,但我现在在另一个程序中重用它.有任何想法吗?

谢谢

cas*_*nca 5

这一行:

std::vector<entry> data;
Run Code Online (Sandbox Code Playgroud)

创建一个空向量,您将传递给它my_filedata[i]在其中进行访问.您需要为元素保留空间,然后才能访问向量中的任意索引.例如:

std::vector<entry> data(maxItems);
Run Code Online (Sandbox Code Playgroud)

  • 哇 !好眼! (2认同)