瞭解std::set.insert
& std::vector
行爲。 請考慮以下情形:按值傳遞,沒有與std :: vector賦值的深層副本?
A.H
class A {
uint id;
vector<double> values;
operator<(const A& argA) const;
}
A.cpp
A::A(uint argId, vector<double> argValues) {
this->id = argId;
this->values = argValues;
}
A::operator<(const A& argA) const {
// it's guaranteed that there's always at least one element in the vector
return this->values[0] < argA.values[0];
}
B.cpp
std::set<A> mySet;
for (uint i = 0; i < (uint) 10; i++)
{
vector<double> tempVector(3);
for (uint j = 0; j < (uint) 3; j++) {
tempVector[j] = j;
}
myset.insert(A(i + 1, tempVector));
}
在我的理解中,tempElement
擁有一個深度複製的向量(值),因爲vector
在構造函數中按值傳遞並被賦值。因此,循環我不應該打破我的設置添加元素。但插入*tempElement
休息 - SIGSEV。在我的邏輯這應該工作......每一個幫助表示讚賞!
編輯:代碼在插入過程中(第二個元素)崩潰; set調用LT-運算符,嘗試訪問傳入參數的向量 - 但不能。在創建A之前,我通過id和向量,檢查傳遞的向量是否包含正確的元素。
爲什麼動態分配tempElement?您的代碼中存在內存泄漏(tempElement未被刪除)。你可以像這樣在一行中完成:myset.insert(A(i + 1,tempVector)); – 2012-01-05 18:56:41
刪除myset時會被刪除。它調用所有包含元素的析構函數。 – Eric 2012-01-05 18:58:00
什麼是tempComponents? – Zac 2012-01-05 18:58:51