2015-05-06 28 views
-3

我只是不能混淆我的話,它讓我得到了任何我不想要的東西。 我沒有錯誤,沒有警告,但磨片,我把我的std字符串:: out_of_range如何混合一個詞? C++

#include <iostream> 
#include <string> 
#include <random> 
#include <chrono> 

using namespace std; 

string melangeLettre(string mot); 
int main() 
{ 
    cout << "Saisissez un mot mystere: \n> "; 
    string motMystere{}; 
    cin >> motMystere; 

    cout << "Quel est ce mot ?\n"; 
    string const newMot{melangeLettre(motMystere)}; 
    cout << newMot << endl; 

    return {0}; 
} 

string melangeLettre(string mot) 
{ 
    size_t random = chrono::system_clock::now().time_since_epoch().count(); 
    mt19937 gen{random}; 
    string newMot{}; 

    for (unsigned int i{}; i < mot.size(); ++i) 
    { 
     uniform_int_distribution<> getNbr(0, mot.size()); 
     int const alea{mot[getNbr(gen)]}; 

     newMot.push_back(alea); 
     mot.erase(alea, 1); 
    } 

    return newMot; 
} 

的問題是「melangeLettre」功能,請有人能幫助我解決呢?

+1

如果你想爭奪你應該使用['的std :: random_suffle()'](字符串http://en.cppreference.com/w/ cpp/algorithm/random_shuffle) – NathanOliver

+0

是算法包含,但我不想使用ready函數。 – user3813238

+0

那你得到了什麼結果?如果不是錯誤或警告?這些琴絃是不是洗牌?他們是空的還是重複的? –

回答

1

您正在使用隨機字母的字符值作爲要擦除的字符的索引。我認爲你需要記下你的隨機位置getNbr(gen),並將其用作erase()的字符。

此外,您的for()循環將無法正常工作,因爲您的單詞mot的大小不斷變化。

最後您的整數分佈是包括範圍。

這與上述更正:

#include <random> 
#include <chrono> 
#include <iostream> // need this 

using namespace std; 

string melangeLettre(string mot); 
int main() 
{ 
    cout << "Saisissez un mot mystere: \n> "; 
    string motMystere{}; 
    cin >> motMystere; 

    cout << "Quel est ce mot ?\n"; 
    string const newMot{melangeLettre(motMystere)}; 
    cout << newMot << endl; 

    return {0}; 
} 

string melangeLettre(string mot) 
{ 
    size_t random = chrono::system_clock::now().time_since_epoch().count(); 
    mt19937 gen{random}; 
    string newMot; 

// for (unsigned int i{}; i < mot.size(); ++i) 
    while(!mot.empty()) // mot keeps changing size so use this 
    { 
//  uniform_int_distribution<> getNbr(0, mot.size()); 
     uniform_int_distribution<> getNbr(0, mot.size() - 1); // range inclusive! 

     auto pos {getNbr(gen)}; // store the position of the letter 
     auto alea {mot[pos]}; 

     newMot.push_back(alea); 
     mot.erase(pos, 1); // erase the letter from the stored position 
    } 

    return newMot; 
} 
+0

哦,是的問題是for循環! 非常感謝你:) – user3813238