C ++如何在不使用标准库中的shuffle函数的情况下对矢量进行混洗?

时间:2014-10-30 06:15:08

标签: c++ vector

由于一些奇怪的原因,我有一个赋值来使用C ++标准库中提供的shuffle或random_shuffle函数来重载的内容而不用。以下是一些具有(无功能)功能的基本代码,可以让您更清楚地了解我的目标:

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{

}
// end function

int main(void)
{
    srand(time(0));

    vector<string> names;
    names.push_back("Sally");
    names.push_back("Sue");
    names.push_back("Bob");
    names.push_back("Fred");


    cout << "Your names:" << endl;
    for (int i = 0; i < names.size(); i++)
    {
        cout << i + 1 << ". " << names[i] << endl;
    }

    cout << "Press Enter to shuffle.";
    cin.get();

    shuffle_vector(names);

    cout << "\nYour shuffled names:" << endl;
    for (int i = 0; i < names.size(); i++)
    {
        cout << i + 1 << ". " << names[i] << endl;
    }
    cin.get();
}

我的想法是:

  1. &#34;的push_back&#34;用于创建临时点的向量
  2. 将一个索引随机分配到临时点
  3. 将一个索引随机分配到新空白点
  4. 将索引放在最后剩余的空索引
  5. &#34; pop_back&#34;矢量到原始大小
  6. (与数组中的切换索引一样)

    我不知道如何执行此操作,但更重要的是 - 如果这甚至可行,或者它是最好的方法。你会怎么做?

1 个答案:

答案 0 :(得分:0)

的Bam!弄清楚这真的很有趣!

我使用rand和一个“for”循环,迭代100次以随机化它。我还添加了一个在洗牌完成后删除的“临时”索引。

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
    for (int i = 0; i < 100; i++)
    {
        int randomIndex = rand() % names.size();
        int randomIndex2 = rand() % names.size();
        if (randomIndex2 == randomIndex) // make sure the two random values aren't the same
        {
            do {
                randomIndex2 = rand() % names.size();
            } while (randomIndex2 == randomIndex);
        }
        names.push_back("temporary"); // create temporary index at the end of the vector
        int last_index_number = (names.size() - 1);
        names[last_index_number] = names[randomIndex];
        names[randomIndex] = names[randomIndex2];
        names[randomIndex2] = names[last_index_number];
        names.pop_back(); // bring vector back to original size
    }
}
// end function

int main(void)
{
    srand(time(0));

    vector<string> names;
    names.push_back("Sally");
    names.push_back("Sue");
    names.push_back("Bob");
    names.push_back("Fred");


    cout << "Your names:" << endl;
    for (int i = 0; i < names.size(); i++)
    {
        cout << i + 1 << ". " << names[i] << endl;
    }
    cout << "Press Enter to shuffle.";
    cin.get();
    shuffle_vector(names);

    cout << "\nYour shuffled names:" << endl;
    for (int i = 0; i < names.size(); i++)
    {
        cout << i + 1 << ". " << names[i] << endl;
    }
    cin.get();
}