我收到一个我不理解的奇怪的段错误。
will@will-mint ~/code/byun-sp15 $ g++ -g all_pairs.cpp
will@will-mint ~/code/byun-sp15 $ ./a.out
Please enter filename:
table.txt
Segmentation fault
正如您从cout位置看到的那样,它在
cin>>filename;
中是段错误的,这是主要功能:#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
using std::vector;
int main()
{
int n;
string filename;
cout << "Please enter filename: " << endl;
cin >> filename;
cout << "FLAG FLAG FLAG";
ifstream fin(filename.c_str());
if (!fin.is_open()) {
cout << "ERROR: file not found. Exiting..." << endl;
return -1;
}
fin >> n;
vector<Table> tables;
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fin >> temp;
tables[0].data[i][j] = temp;
}
}
for (int i = 1; i < n-1; i++) {
tables.push_back(calc_next_table(tables, i, n));
}
return 0;
}
我真的很像个白痴,我从来没有碰过这个。我找到了this,但是并没有解决。我什至尝试了gdb(我真的不知道如何使用),而我得到的只是这个:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401ae8 in std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::operator[] (this=0x0, __n=0) at /usr/include/c++/4.8/bits/stl_vector.h:771
771 { return *(this->_M_impl._M_start + __n); }
(gdb) list
766 * out_of_range lookups are not defined. (For checked lookups
767 * see at().)
768 */
769 reference
770 operator[](size_type __n)
771 { return *(this->_M_impl._M_start + __n); }
772
773 /**
774 * @brief Subscript access to the data contained in the %vector.
775 * @param __n The index of the element for which data should be
看起来矢量正在做一些时髦的事情,但是我什至还没有声明我的矢量!有任何想法吗?
编辑:我喜欢@neilson的答案,但以下仍然抛出segfault:
fin >> n;
vector<Table> tables;
Table t;
tables.push_back(t);
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fin >> temp;
tables[0].data[i][j] = temp;
}
}
cout << "FLAG FLAG FLAG" << endl;
表有一个元素,称为
vector<vector<int>>
的data
。我也该发布吗? 最佳答案
我认为问题出在这里:
fin >> n;
vector<Table> tables;
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fin >> temp;
tables[0].data[i][j] = temp; // HERE
}
}
访问向量时该向量为空。
做
tables.push_back(..something..)
第一。
像这样:
fin >> n;
vector<Table> tables;
Table someTable; // Create a table
tables.push_back(someTable); // Put it in the vector
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fin >> temp;
tables[0].data[i][j] = temp;
}
}
编辑:
由于您告诉Table也有一个向量,因此您需要更改:
tables[0].data[i][j] = temp;
也要使用push_back。
除非先添加元素,否则无法访问向量中的元素。
如果表具有成员:
vector<vector<int>> data;
您可能会做类似的事情:
fin >> n;
vector<Table> tables;
Table someTable; // Create a table
tables.push_back(someTable); // Put it in the vector
int temp;
for (int i = 0; i < n; i++) {
tables[0].data.push_back(vector<int>()); // create the i'th vector and insert it
for (int j = 0; j < n; j++) {
fin >> temp;
tables[0].data[i].push_back(temp); // Use push_back
}
}
注意:我还没有测试过这个,因为我不在编译器附近...但是我认为这样可以。