C ++随机播放向量 [英] C++ Shuffle Vector

查看:221
本文介绍了C ++随机播放向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到其他线程,但没有似乎回答我的问题。我试图在向量上使用 shuffle()函数,但我不断收到错误:

  deck_of_cards.cpp:34:5:错误:没有匹配函数调用'shuffle'
shuffle(deck.begin(),deck.end(),std :: default_random_engine种子));
^ ~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/algorithm:3049:10 :note:候选函数[with
_RandomAccessIterator = std :: __ 1 :: __ wrap_iter< Card *>,_UniformRandomNumberGenerator = std :: __ 1 :: linear_congruential_engine< unsigned int,48271,0,
2147483647>不可行:期望第三个参数的l值
void shuffle(_RandomAccessIterator __first,_RandomAccessIterator __last,
^
生成错误
pre>

我使用clang ++作为我的编译器,这是我的代码是抛出的错误:

  void DeckOfCards :: shuffleDeck()
{
seed = std :: chrono :: system_clock :: now()。time_since_epoch()。count();
shuffle(deck.begin(),deck.end(),std :: default_random_engine(seed));
}

我在程序中有所有正确的 #includes 我是C ++的新手,这基本上是一个Java程序,有我试图转换为C ++。任何帮助将不胜感激!

解决方案

编译器告诉你它期望一个左值ar第三个参数,你给它一个右值的临时对象)。



尝试此操作:

  auto gen = std :: default_random_engine种子); 
shuffle(deck.begin(),deck.end(),gen);

请注意, std :: shuffle 应接受一个右值作为第三个参数,因此符合标准的实现将接受您的代码。


I have seen other threads on this but none seem to answer my question. I'm trying to use the shuffle() function on a vector but I keep getting an error:

deck_of_cards.cpp:34:5: error: no matching function for call to 'shuffle'
shuffle (deck.begin(), deck.end(), std::default_random_engine(seed));
^~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/algorithm:3049:10: note: candidate function [with
  _RandomAccessIterator = std::__1::__wrap_iter<Card *>, _UniformRandomNumberGenerator = std::__1::linear_congruential_engine<unsigned int, 48271, 0,
  2147483647>] not viable: expects an l-value for 3rd argument
void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
     ^
1 error generated.

I'm using clang++ as my compiler and this is my code that is throwing the error:

void DeckOfCards::shuffleDeck()
{
    seed = std::chrono::system_clock::now().time_since_epoch().count();
    shuffle (deck.begin(), deck.end(), std::default_random_engine(seed));
}

I do have all the correct #includes in my program. I'm fairly new to C++ and this is basically a Java program that I have that I'm trying to convert to C++. Any help would be appreciated!

解决方案

The compiler is telling you that it expects an lvalue ar third parameter, and you are giving it an rvalue (in the form of a temporary object).

Try this:

 auto gen = std::default_random_engine(seed);
 shuffle (deck.begin(), deck.end(), gen);

Note that std::shuffle should accept an rvalue as third parameter, so a standards-compliant implementation would have accepted your code.

这篇关于C ++随机播放向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆