【发布时间】:2015-10-22 01:05:56
【问题描述】:
我尝试了相对简单的任务 - 创建一个向量并对其进行排序。但不幸的是,当从堆栈中销毁向量时,它会因 SIGTRAP 而失败。当我删除排序时,它可以,但我更需要它。
我已将问题范围缩小到尽可能小的源代码。当我运行它时,我收到 Windows 错误“程序意外停止”。当我使用附加的 GDB 时,它会在完成第一个 while 循环后突出显示向量析构函数。 (见下图)
vector<Vec> veci(n); 和resize(n) 我都试过了。我感觉这可能是由于排序算法以某种方式对向量中不存在的项目进行排序引起的,但代码并没有说明问题......你看到了吗?
Windows 10,mingw gcc
#include <stdio.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <ctime>
#include <stack>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>
#include <sstream>
using namespace std;
struct Vec {
int cena;
int vaha;
float pomer;
bool operator < (const Vec& oth) const
{
return !(pomer < oth.pomer);
}
};
int main(int argc, char** argv) {
stringstream file;
file << "9550 40 600 14 223 38 230 3 54 1 214 13 118 4 147 15 16 2 104 5 56 49 154 40 106 24 234 18 34 33 195 7 74 10 129 12 159 42 37 41 10 11 185 6 243 45 87 32 57 20 87 9 26 16 201 39 0 23 128 39 194 21 10 46 1 8 28 30 59 26 130 35 160 22 91 34 180 19 16 31 1 17 72";
while (file.good()) {
int id;
int n;
int M;
file >> id;
file >> n;
file >> M;
vector<Vec> veci;
veci.resize(n);
for (int i = 0; i < n; i++) {
int c, v;
file >> v;
file >> c;
veci[i].vaha = v;
veci[i].cena = c;
veci[i].pomer = c / (v+1);
}
sort(veci.begin(), veci.end());
}
printf("end");
return 0;
}
【问题讨论】:
-
一次this,我怀疑你真的想要截断整数除法
c / (v+1)。如果循环问题是导致错误的问题(肯定是错误的),请告诉我,以便我可以关闭它。
标签: c++ sorting vector stl mingw