我有一個帶有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
};
移動任務怎麼樣?此外,'random_shuffle'在C++ 14中被棄用,並在C++ 17中被刪除;你應該使用'std :: shuffle'。 –
你問'std :: random_shuffle'嗎?你沒有'使用名稱空間標準;'而且你限定了那個名字空間中的所有其他類型,所以我很困惑。 – user2079303
@ user2079303是的我的意思是'std :: random_shuffle'。在這個項目中,我使用了'使用命名空間std',但是我在這裏添加了std :: cleanliness並忘記了一個。 – Michiel