2011-03-17 54 views
0

嗨,我有以下C++程序: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; 

} 

不知怎的,它总是给我的my_file方法不好的访问。该计划实际上应如下:

  1. 读取包含一个标题和一个换行分隔
  2. 输出一切成一个文件10个双打多个文件,所以它看起来是这样的:

    1. 文件\ t 2.文件\ t 3.文件\ t ...

    2. 文件\ t 2.文件\ t 3.文件\ t ...

    3. 文件\ t 2.文件\ t 3.文件\ t ...

    4. 文件\ t 2.文件\ t 3.文件\ t ...

    5. 文件\ t 2.文件\ t 3.文件\ t ...

这实际上已经工作,但我现在在不同的程序重复使用它。有任何想法吗?

谢谢

+0

您是否仔细检查过输入文件?您的演员阵容增加一倍可能会失败并导致问题。 – Pepe 2011-03-17 17:13:37

+0

我做到了;)我经常遇到这个问题,但是谢谢 – 2011-03-17 17:23:10

回答

5

这条线:

std::vector<entry> data; 

创建一个空的载体,它要传递到my_file和内部访问data[i]。您需要为元素保留空间,然后才能访问向量中的任意索引。例如:

std::vector<entry> data(maxItems); 
+2

哇!好眼睛! – Pepe 2011-03-17 17:15:26

+0

多数民众赞成我是用这个“c”变量像这样std :: vector data(c),但是我在write_file方法中得到一个错误, – 2011-03-17 17:26:15

+0

我试过这个:std :: vector data(c );对于(int i = 0; i 2011-03-17 17:31:11