【发布时间】:2018-04-09 18:11:48
【问题描述】:
我是 C++ 新手,我正在尝试读取写入文件中的每一行的前四个单词,并为其分配一个我的类的对象,即 Detected_Object。我想将这些对象存储到向量中。当我尝试将我的类的 push_back 对象放入分段错误(核心转储)错误时。
其他矢量方法,如 size、max_size() 和 capacity() 在矢量上运行良好,但在 push_back() 上却出错。
到目前为止,我已经尝试了以下解决方法: 1.尝试使用指向对象的指针向量而不是对象本身。 2.尝试用new关键字初始化vector,然后使用它。 3. 调整矢量大小以容纳 10 个元素。 但以上都没有奏效,我不知道我做错了什么。代码库如下:
vector<Detected_Object*> objects;
ifstream fp;
string filename="../data/area_info/"+to_string(i)+".jpg.info";
fp.open(filename);
int left,right,top,bottom;
string line;
//end tracking if list of detected object is null
if(fp && fp.peek() == EOF){
return;
}else{
//read all detected objects from single frame
while (getline(fp, line)) {
int counter=0;
istringstream buf(line);
istream_iterator<std::string> beg(buf), end;
std::vector<std::string> tokens(beg, end); // done!
for(string& s: tokens){
std::cout << '"' << s << '"' << '\n';
if(counter==0){
left=stoi(s);
}else if(counter == 1){
right =stoi(s);
}else if(counter == 2){
top = stoi(s);
}else if(counter == 3){
bottom = stoi(s);
counter=0;
cout<<"value of left coordinate: "<<left<<" right: "<<right<<" top: "
<<top<<" bottom: "<<bottom<<endl;
break;
}
counter++;
}
Detected_Object obj(left,right,top,bottom);
cout<<"max sizeof vector of detected objects ";
cout<<objects.max_size();
//cout<<"detected object left: "<<obj.left<<"right: "<<right<<"top: "<<obj.top<<"bottom: "<<obj.bottom;
objects.push_back(&obj);
}
}
编辑:
以下代码也不起作用:
vector<Detected_Object> objects = vector<Detected_Object>();
Detected_Object obj;
ifstream fp;
string filename="../data/area_info/"+to_string(i)+".jpg.info";
fp.open(filename);
int left,right,top,bottom;
string line;
//end tracking if list of detected object is null
if(fp && fp.peek() == EOF){
return;
}else{
//read all detected objects from single frame
while (getline(fp, line)) {
int counter=0;
istringstream buf(line);
istream_iterator<std::string> beg(buf), end;
std::vector<std::string> tokens(beg, end); // done!
for(string& s: tokens){
std::cout << '"' << s << '"' << '\n';
if(counter==0){
left=stoi(s);
}else if(counter == 1){
right =stoi(s);
}else if(counter == 2){
top = stoi(s);
}else if(counter == 3){
bottom = stoi(s);
counter=0;
cout<<"value of left coordinate: "<<left<<" right: "<<right<<" top: "
<<top<<" bottom: "<<bottom<<endl;
break;
}
counter++;
}
obj = Detected_Object(left,right,top,bottom);
objects.push_back(obj);
}
}
请帮我找出解决这个错误的方法。
谢谢。
【问题讨论】:
-
错误是什么?顺便说一句,即使您没有收到错误,您推入向量的指针在您将其推入向量后仅一行就无效。为什么你认为你需要一个指针向量而不是一个普通的向量?
-
摆脱这个错误的方法是使用调试器;)
-
我无法告诉您这是否是问题所在,但您正在将指向本地对象的指针存储在向量中。这些对象超出范围并让您的向量充满悬空指针。如果你真的必须在向量中有一个指针,那么你需要类似
vector<std::unique_ptr<Detected_Object>> objects; -
你可以试试这个:
vector<Detected_Object*> objects = vector<Detected_Object*>();,你只声明了向量但你没有初始化它。 -
@DariusDuesentrieb 这不会改变任何事情。
vector<Detected_Object*> objects;与vector<Detected_Object*> objects = vector<Detected_Object*>();相同
标签: c++ vector segmentation-fault coredump