C ++向量访问错误 [英] c++ vector bad access
问题描述
我有以下c ++程序:
Hi I have the following c++ program:
#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方法.该程序实际上应满足以下条件:
Somehow it always gives me a bad access in the my_file method. The program should actually to the following:
- 读取多个包含标题和十个由换行符分隔的双打的文件
-
将所有内容输出到一个文件中,因此看起来像这样:
- read multiple files that contain a caption and ten doubles seperated by a newline
output everything into one file so it looks like this:
-
文件\ t 2.文件\ t 3.文件\ t ...
file \t 2. file \t 3. file \t ...
文件\ t 2.文件\ t 3.文件\ t ...
file \t 2. file \t 3. file \t ...
文件\ t 2.文件\ t 3.文件\ t ...
file \t 2. file \t 3. file \t ...
文件\ t 2.文件\ t 3.文件\ t ...
file \t 2. file \t 3. file \t ...
文件\ t 2.文件\ t 3.文件\ t ...
file \t 2. file \t 3. file \t ...
这实际上已经起作用了,但是我现在在另一个程序中重用了它.有什么想法吗?
This actually worked already, but i reused it now in a different program. Any ideas?
谢谢
推荐答案
此行:
std::vector<entry> data;
创建一个空向量,将其传递给my_file
并在其中访问data[i]
.您需要为元素保留空间,然后才能访问向量中的任意索引.例如:
creates an empty vector, which you are passing to my_file
and accessing data[i]
within. You need to reserve space for the elements before you can access arbitrary indices in the vector. For example:
std::vector<entry> data(maxItems);
这篇关于C ++向量访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!