簡體   English   中英

為什么std :: sort()會改變排序的向量?

[英]Why does std::sort() change the sorted vector?

這是問題所在:

在我的第一堂課中,我有一個向量,一個雙變量,我重載比較運算符。 這是相關代碼:

class City
{
    double distance;
    std::vector<int> coordinates;

    bool operator<(const City& city) const
    {   
        return this->distance < city.distance;
    } 

    // same for the greater-than operator but changing "<" to ">"
};

在另一個班級,我有一個城市的向量,每次滿足條件時我都要對它進行排序。 為此我有一個結構定義如下:

編輯:(參考而不是值)

struct CitySortHelper {
    bool operator() (const City &x, const City &y) const { return x < y; } 
} city_sort;

現在問題部分,當我對矢量新的City對象進行排序時,我無法解釋原因:

編輯:

// this prints all current objects in the vector
for (int i = 0; i < totalCities; i++) {
    std::cout << cities->at(i) << std::endl;
}

// after the following line I get new City objects in the 
// vector, that weren't there before the sort. The new objects
// always have distance = 0 and random values in the coordinates
std::sort(cities->begin(), cities->end(), city_sort);

// using the sort with no predicate also gives the same faulty results
std::sort(cities->begin(), cities->end());

編輯:(復制構造函數和賦值運算符)

City(const City &city)
{
    this->distance = city.distance;
    this->coordinates = city.coordinates;
}

City& operator= (const City &city)
{
    this->distance = city.distance;
    this->coordinates = city.coordinates;

    return *this;
}

奇怪的是,只有當我按照升序對City對象進行排序時才會發生這種情況,即如果我將CitySortHelper中的CitySortHelper從“<”更改為“>”,一切正常。

任何想法為什么會這樣? 任何幫助表示贊賞。

CitySortHelper需要通過const引用而不是值來獲取參數。 要記住的另一件事是sort使用City賦值運算符; 檢查您的賦值運算符是否正常工作。 處理這兩個問題應該解決問題。

如果要保留順序,則不應使用std::sort() ,應使用std::stable_sort() stable_sort保證元素保持其相對順序, sort不保持。

此外,這似乎不是sort是你的問題。 似乎City對象被推入到某個地方的向量中,並且您沒有注意到它們,因為您正在檢查變量的大小而不是向量的迭代器。 嘗試這樣打印,並告訴我們出來的內容:

for (std::vector <City> ::iterator it = cities->begin(); it != cities->end(); ++it) {
    std::cout << *it << std::endl;
}

更改您的排序助手

bool operator() ( const City& x , const City& y) const

並檢查City復制構造函數和賦值運算符是否正確

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM