我正在尝试创建对象类型teaStep的数组,以及尝试将列表重新排序为随机列表。
函数makeSteps
用于初始化变量并将其存储在数组中并输出。
函数randomizeSteps
的目的是在输出新数组之前,先创建一个整数数组并随机化其顺序。
只是想知道这是否是正确的方法。
[编辑]
使用向量,我现在有了这个:
auto makeSteps()
{
auto all_steps = std::vector<teaStep>{};
all_steps.emplace_back("Pick your tea", 1);
all_steps.emplace_back("Boil water", 2);
all_steps.emplace_back("Get tea bag in mug or pot", 3);
all_steps.emplace_back("Pour boiled water over teabag", 4);
all_steps.emplace_back("Wait!", 5);
all_steps.emplace_back("Remove teabag", 6);
all_steps.emplace_back("Add milk and/ or sugar", 7);
all_steps.emplace_back("Mix, drink and enjoy", 8);
return all_steps;
}
auto randomizeSteps()
{
vector <int> ranstep;
for (int i = 1; i < 9; i++)
ranstep.push_back(i);
auto rng = std::default_random_engine{};
std::shuffle(std::begin(ranstep), std::end(ranstep), rng);
return ranstep;
}
要补充一点,一旦完成,我就必须能够利用向量中的对象,但是当我尝试这样做时,我得到一个错误,如下例所示:
//should go through the object in vectors, and compare the field Order, to int a.
teaStep findStep(int a, std::vector<teaStep> vectors)
{
for (int b = 0; b < 8; b++)
{
teaStep test = vectors[b];
if (test.getOrder == a)
return test;
}
}
我得到的错误是“没有从int到int(...)的转换
答案 0 :(得分:2)
您在此处返回指向局部变量的指针:
teaStep arr[] = /* ... */;
return arr;
}
退出arr
(在结束makeSteps
时),}
的生存期结束。而且,每当您操纵makeSteps
的返回值时,都会产生垃圾。
尝试并使用std::vector
而不是普通的C数组,例如:
auto make_steps()
{
auto steps = std::vector<teaStep>{};
steps.emplace_back("Pick your tea", 1);
steps.emplace_back("Boil water", 2);
steps.emplace_back("Get tea bag in mug or pot", 3);
steps.emplace_back("Pour boiled water over teabag", 4);
steps.emplace_back("Wait!", 5);
steps.emplace_back("Remove teabag", 6);
steps.emplace_back("Add milk and/ or sugar", 7);
steps.emplace_back("Mix, drink and enjoy", 8);
return steps;
}
答案 1 :(得分:0)
除了@YSC所说的以外,请不要使用std:random_shuffle
。是deprecated。
改为使用std::shuffle
。
#include <algorithm>
#include <random>
auto makeSteps()
{
auto steps = std::vector<teaStep>{};
steps.emplace_back("Pick your tea", 1);
steps.emplace_back("Boil water", 2);
steps.emplace_back("Get tea bag in mug or pot", 3);
steps.emplace_back("Pour boiled water over teabag", 4);
steps.emplace_back("Wait!", 5);
steps.emplace_back("Remove teabag", 6);
steps.emplace_back("Add milk and/ or sugar", 7);
steps.emplace_back("Mix, drink and enjoy", 8);
return steps;
}
auto randomizeSteps()
{
std::vector<int> ranstep(10) ; // vector with 10 ints.
std::iota (std::begin(v), std::end(v), 0); // Fill with 0, 1, ..., 9.
auto rng = std::default_random_engine{};
std::shuffle(std::begin(ranstep), std::end(ranstep), rng);
return ranstep;
}