Random_shuffle修改洗牌对象(c++11)

random_shuffle modifies shuffled objects (c++11)

本文关键字:对象 c++11 shuffle 修改 Random      更新时间:2023-10-16

我有一个包含Tour对象的向量,我想对它们进行洗牌。幸运的是有一个函数random_shuffle()。我在洗牌之前和之后打印对象,但是,对象的一个字段根本没有洗牌。

首先想到的是复制或移动构造函数不正确。在两个构造函数中使用cout后,我发现使用了move构造函数。奇怪的是,构造函数对我来说似乎是正确的。

下面给出了代码和move构造函数。回想一下,洗牌后只有一个字段是错误的,即d_penalty。有人能帮我解决这个错误吗?

std::vector<Tour> tours;
// Fill vector with 4 tour objects
std::cout << "Print vectorn";
for (Tour const &tour: tours)
  std::cout << tour << std::endl;
std::cout << "Shufflen";
std::random_shuffle(tours.begin(), tours.end());
std::cout << "Print vectorn";
for (Tour const &tour: tours)
  std::cout << tour << std::endl;  

move构造函数定义如下:

#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 movedn";
}

类定义如下:

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
};

std::random_shuffle 交换元素。默认交换,由std::swap实现,同时使用move构造和move赋值。

如果没有move赋值操作符,则使用copy赋值操作符。因为你的move构造函数正确地处理了d_penalty,听起来你的拷贝赋值操作符没有正确地实现。

一般来说,可以从move语义中获益的类应该同时具有move构造函数和move赋值操作符。在可能的情况下,特殊成员函数应该定义为= default;

另外,std::random_shuffle在c++ 14中被弃用,在c++ 17中被删除;您应该在<random>头中使用std::shuffle和URNG,例如std::mt19937