【发布时间】:2017-01-12 04:43:39
【问题描述】:
我正在尝试设计一个随机选择五个字符串中的三个并将它们显示在屏幕上的函数。这是我到目前为止所拥有的。它运行但没有任何内容打印到屏幕上。
#include "BoxOfProduce.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
BoxOfProduce::BoxOfProduce()
:choices{""}, bundles{""}
{
}
vector<string> BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}
#ifndef BOXOFPRODUCE_H
#define BOXOFPRODUCE_H
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class BoxOfProduce
{
public:
BoxOfProduce();
string getBundles();
void setBundles(string b);
vector<string> randomize();
private:
string bundles[3];
const string choices[5];
string random;
};
#endif // BOXOFPRODUCE_H
#include <iostream>
#include "BoxOfProduce.h"
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
int main()
{
srand(time(0));
BoxOfProduce bo;
bo.randomize();
auto vector<string> randomResult = bo.randomize();
for (const auto& result : randomResult){
cout << result << endl;
}
}
我现在更新了我的代码,但仍然没有打印输出。虽然我收到一个错误: 错误:C++98 模式下不允许基于范围的“for”循环
我以前从未使用过 auto。因此,我们将不胜感激。
【问题讨论】:
-
为什么,哦,为什么,当
rand吸得这么厉害时,人们还坚持使用它。只需使用<random>的东西 -请。 -
这不应该编译。在函数中,
random是循环本地的;它不应该能够在循环之外返回。在循环外声明random,然后从循环内删除类型。 -
@JesperJuhl:可能是因为
<random>的界面比较繁琐,而rand()适用于大多数人的情况。 -
另外,您需要将
random改为字符串列表,并添加到其中而不是在每个循环上覆盖。 -
@BenjaminLindley
<random>有一个很好的界面,分离引擎和发行版是一个明智的设计选择。