怎么混淆一个字? C ++

时间:2015-05-06 19:21:38

标签: c++

我只是不能混淆我的话,它给了我任何我不想要的东西。 我没有错误,没有警告,但是我放了一个字符串,我有std :: out_of_range

alertSearchServiceImpl_v4

问题在于'melangeLettre'功能,有人可以帮我解决这个问题吗?

1 个答案:

答案 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;
}