我需要从另一个类的 std::vector 构造一个 std::discrete_distribution 。然而,我得到的一切都是错误的
无法创建大于 max_size() 的 std::vector
我试图将代码简化为基础(也错过了所有包含的内容,因为其他一切都工作正常)。另外,在花费了很短的时间尝试调试之后,我使用了一些控制台打印来找到我认为导致此问题的问题。
A类.h
class ClassA.h {
private:
std::vector<double> weights;
public:
ClassA();
[[nodiscard]] std::vector<double> getWeights();
Run Code Online (Sandbox Code Playgroud)
A类.cpp
ClassA::ClassA() {
for (int i = 0; i < 50; i++) {
initialPheromone.emplace_back(1);
std::cout << " " << initialPheromone[i]; // TESTING
}
}
std::vector<double> ClassA::getWeights() {
return weights;
}
Run Code Online (Sandbox Code Playgroud)
B.h类
class ClassB {
private:
ClassA *variable;
void someFun();
Run Code Online (Sandbox Code Playgroud)
B类.cpp
ClassB::ClassB(ClassA *classA1){
variable = classA1;
}
void someFun() {
// TESTING
for (auto thing = variable->getWeights().begin();
thing != variable->getWeights().end();
++thing) {
std::cout << *thing << " ";
}
// END OF TESTING
std::discrete_distribution<> firstDistribution( variable->getWeights().begin(),
variable->getWeights().end() );
}
Run Code Online (Sandbox Code Playgroud)
供参考 CMAKE_CXX_STANDARD = 23
在 A 类的构造函数中,我的 cout 测试打印了 50 个 1 - 正如预期的那样。
在 B 类中,打印出一些奇怪的内容:1.14165e-313 -1.15737e+57 1 1 1...
总共仍然有 50 个值。
为什么前两个会发生变化?
此外,这些极端值是否因为太大/太小而破坏了我的分布?
variable->getWeights()每次调用时都会返回一个新向量。如果您不保存向量,它将在语句末尾被销毁。
因此,auto thing = variable->getWeights().begin()您创建一个新向量并获取其begin迭代器。然后你破坏这个向量。然后取消引用迭代器*thing。然后thing != variable->getWeights().end()创建一个新的向量,看看thing它是否是结束迭代器......等等......
解决方案:您可以getWeights返回对 中向量的引用ClassA,而不是新向量。您可以添加,const以便调用者不允许更改向量,例如variable->getWeights().push_back(5);
const std::vector<double>& ClassA::getWeights() {
//^^^^^ ^
Run Code Online (Sandbox Code Playgroud)