我嘗試相對簡單的任務 - 創建一個向量並對其進行排序。但不幸的是,當從堆棧中銷燬載體時,SIGTRAP失敗。當我刪除這種類型時,它確定,但我更需要它。C++排序stl向量失敗(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;
}
對於一次[此](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-認爲是錯誤的),我懷疑你真的想要截斷整數除法'c /(v + 1)'。如果環路是導致錯誤的問題(肯定是錯誤的),請告訴我,以便我可以關閉它。 –