2015-06-05 17 views
0

我有一個帶有Tour對象的矢量並且想要對它們進行洗牌。幸運的是有一個功能random_shuffle()。我在洗牌之前和之後打印物體,但是物體的一個區域根本不洗牌。random_shuffle修改混洗對象(C++ 11)

首先想到的是複製或移動構造函數不正確。在兩個構造函數中使用cout之後,我發現使用了移動構造函數。奇怪的是,構造函數對我來說似乎是正確的。

代碼和移動構造函數如下所示。回想一下,洗牌後只有一個字段不正確,即d_penalty。任何人都可以幫助我解決這個錯誤?

std::vector<Tour> tours; 
// Fill vector with 4 tour objects 

std::cout << "Print vector\n"; 
for (Tour const &tour: tours) 
    std::cout << tour << std::endl; 

std::cout << "Shuffle\n"; 
std::random_shuffle(tours.begin(), tours.end()); 

std::cout << "Print vector\n"; 
for (Tour const &tour: tours) 
    std::cout << tour << std::endl; 

此舉構造函數定義如下,

#include "tour.ih" 

/** 
* Move constructor 
*/ 

Tour::Tour(Tour &&other) 
: 
    d_capacity(other.d_capacity), 
    d_demand(other.d_demand), 
    d_feasible(other.d_feasible), 
    d_length(other.d_length), 
    d_time(other.d_time), 
    d_penalty(other.d_penalty), 
    d_tour(std::move(other.d_tour)) 
{ 
    cout << "Tour moved\n"; 
} 

的類的定義如下,

class Tour 
{ 
    // Current information about the tour 
    int d_capacity; // Remaining capacity of the truck 
    int d_demand;  // Total demand of all customers in the tour 
    bool d_feasible; // Is the tour feasible in capacity 
    double d_length;  // Length of the current tour 
    double d_time;  // Driving time plus serving time 
    double d_penalty;  // The penalty for infeasibility 

    // The tour itself 
    std::vector<City const *> d_tour; 

    public: 
    // Other functions 

    private: 
    // More functions 
}; 
+0

移動任務怎麼樣?此外,'random_shuffle'在C++ 14中被棄用,並在C++ 17中被刪除;你應該使用'std :: shuffle'。 –

+0

你問'std :: random_shuffle'嗎?你沒有'使用名稱空間標準;'而且你限定了那個名字空間中的所有其他類型,所以我很困惑。 – user2079303

+0

@ user2079303是的我的意思是'std :: random_shuffle'。在這個項目中,我使用了'使用命名空間std',但是我在這裏添加了std :: cleanliness並忘記了一個。 – Michiel

回答

3

std::random_shuffle互換的元素。默認掉期由std::swap實施,同時使用移動建設和移動分配。

如果您沒有移動賦值運算符,則將使用複製賦值運算符。由於您的移動構造函數確實正確處理d_penalty,這聽起來像您的複製分配操作符沒有正確實現。

通常,可以從移動語義中受益的類應該同時具有移動構造函數和移動賦值運算符。在可能的情況下,特殊成員函數應定義爲= default;

此外,std::random_shuffle在C++ 14中已棄用,並在C++ 17中刪除;您應該在<random>標頭中使用std::shuffle和URNG,例如std::mt19937

+0

請注意,在MSVC2013中,'= default'不適用於move assign/construct。它顯然將在2015年工作。 – Yakk