Random_shuffle修改洗牌对象(c++11)
random_shuffle modifies shuffled objects (c++11)
我有一个包含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
。
相关文章:
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- C++11 中不同类型的对象的 std::array 的替代方案
- 队列未添加对象-C++11
- C++11 中的对象验证逻辑模式
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 为什么编译器在试图初始化具有C 11样式的对象数组时隐含删除构造函数
- 如何在 Windows 上从 C++11 统计信息对象的文件序列号中查找文件名
- 实现功能对象绑定而无需使用C 11
- 启动程序和libocci.so.11.1:无法打开共享对象文件:没有这样的文件或目录
- 子类对象列表重新解释为基类对象列表?(C++11).
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- C 11是否保证将移动垂死的对象而不是复制为参数
- C++11 initializer_list不适用于嵌入对象的文字常量值?
- 在C++11中按值返回构造的对象时,避免复制构造函数调用
- 链接C++17、C++14和C++11对象是否安全
- DirectX 11 基于旋转移动对象
- IE 探索 11 < c++ ATL COM 浏览器帮助程序对象(加载项)来替换 DOM 中的文本
- DirectX 11渲染对象内部
- 我能否使 C++11 类/对象通用线程安全?
- Random_shuffle修改洗牌对象(c++11)