我正在尝试编写一个获取字符串向量并返回指向随机元素的指针的方法.您能告诉我以下代码有什么问题吗?
string* getRandomOption(vector<string> currOptions){
vector<string>::iterator it;
it=currOptions.begin();
string* res;
int nOptions = currOptions.size();
if(nOptions != 1){
int idx = rand() % (nOptions-1);
while (idx!=0){
it++;
idx--;
};
};
res = &(*it);
};
Run Code Online (Sandbox Code Playgroud)
谢谢,李
fre*_*low 10
为什么要返回指针?把事情简单化!
std::string random_option(const std::vector<std::string>& options)
{
return options[rand() % options.size()];
}
Run Code Online (Sandbox Code Playgroud)
因为这适用于任何类型,不仅仅是字符串,我更喜欢通用的解决方案:
template <typename T>
T random_element(const std::vector<T>& options)
{
return options[rand() % options.size()];
}
Run Code Online (Sandbox Code Playgroud)
如果要"返回指向随机元素的指针",则需要传递对向量的引用.现在,它被复制了!
你应该做 :
string* getRandomOption(vector<string> & currOptions)
Run Code Online (Sandbox Code Playgroud)
顺便说return
一下,你的函数目前还没有,你需要添加一个return语句来发送你的指针.