我有一個奇怪的行爲下面的代碼:C++循環掛起,如果任何代碼被添加里面如果條件
struct Mime {
int key;
string value;
};
class Storage {
private:
int Size;
Mime * _storage;
int last = 0;
public:
Storage(int __size) {
Size = __size;
_storage = new Mime[Size + 2];
}
void add(const Mime & __mime) {
for (int x = 0; x < last; x++)
if (_storage[x].key == __mime.key) {}
_storage[last++] = __mime;
}
};
void test2() {
int thisSize = 1000000;
Storage storage(thisSize);
auto start_t = chrono::high_resolution_clock::now();
for (int i = 0; i < thisSize; i++) {
Mime temp;
temp.key = i;
temp.value = "Hey";
storage.add(temp);
}
cout << chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_t).count() << " milliseconds\n" << endl;
}
int main() {
test2();
cout << "Done" << endl;
return 0;
}
在120毫秒我此代碼運行。但是,當我的{}
if (_storage[x].key == __mime.key) {}
這裏面添加一些代碼,就像
if (_storage[x].key == __mime.key) { return; }
或其他任何東西...... 後來我的程序10分鐘跑,有時通過添加return;
或任何其他代碼掛起。當我在此if
條件中添加return;
或任何其他代碼時,我的程序會掛起。在這個(如果)沒有發生在這個過程中,因爲這似乎並沒有運行return;
或任何其他代碼。
有什麼建議嗎?
不要在變量名稱前加下劃線。雙下劃線保留給內部的東西 –
行'_storage [last ++] = __mime;'是可疑的。 – Malice
該代碼是真實的...請在您的系統中運行它...這個_storage [last ++] = __mime沒有問題; – MyJustWorking