2011-03-17 52 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