比较两个静态数组

Compare two static arrays

本文关键字:两个 静态 数组 比较      更新时间:2023-10-16

我有一个问题,如何实现比较两个静态数组,即

string bufferNames[]={"apple","orange","banana","pomegranate","pear"};
string bufferPictures[] = {"apple.bmp","orange.bmp","banana.bmp","pomegranate.bmp","pear.bmp"};

当bufferPictures中的图片加载到屏幕上时,bufferNames中的每个项目都会向某人提供所做的选择。因此,例如,如果我使用rand()函数迭代该列表来获得orange.bmp,我如何才能获得相同的一个对应元素orange和另外两个随机的不正确元素。如有任何帮助,我们将不胜感激。

提前谢谢。

附言:如果需要进一步解决这个问题,就这么说吧。

应该这样做。代码利用了C++11的特性。你会的需要调整它,把它当作家庭作业。

#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
struct Picture {
  std::string name, file;
  bool operator==(const Picture& x) const { return this->name == x.name && this->file == x.file; }
  bool operator!=(const Picture& x) const { return !(*this == x); }
};
int main()
{
  std::vector< Picture > pics = 
    {
      {"apple", "apple.bmp"},
      {"orange", "orange.bmp"},
      {"banana", "banana.bmp"},
      {"pear", "pear.bmp"},
    };
  // determined by random choice
  const Picture& choice = pics[0];
  std::vector< Picture > woChoice;
  std::copy_if(pics.begin(), pics.end(), std::back_inserter(woChoice), 
               [&choice](const Picture& x) {
                 return x != choice;
               });
  // random shuffle the remainder and pick the first
  // two. alternatively and for more efficience use std::random to
  // generate indices
  std::random_shuffle(woChoice.begin(), woChoice.end());
  std::cout << woChoice[0].name << std::endl;
  std::cout << woChoice[1].name << std::endl;
  return 0;
}

因此,例如,如果我使用rand()函数迭代该列表来获得orange.bmp,我如何才能获得相同的一个对应元素orange和另外两个随机的不正确元素。

如果您使用rand()来获得一个介于0和4之间(包括0和4)的数字(我们称之为x)(基于数组中有5个不同的值),那么您可以在两个数组中使用该数字来查找相关的单词和图像。

要获得另一个随机错误元素,可以在循环中调用rand(),直到获得除x之外的值。让我们称之为y

要获得另一个随机不正确的元素,可以在循环中调用rand(),直到获得除xy之外的值。

还有其他方法可以做到这一点,但这可能是最容易理解和实现的。

  1. 数组中的名称彼此对应。所以,如果你需要水果数字i,以并行方式获取bufferNames[i]和bufferPictures[i]。

  2. 确保名称是平行的。只需制作第二个阵列来自第一阵列元件的元件。

  3. 对于0..n-1范围内的随机,不包括元素编号i,j(j>i),计数为:

    temp=随机(n-3);k=(温度>=i?温度+1:temp);k=(k>=j?k+1:k);

再拿bufferNames[k]和bufferPictures[k]。

这并不简单,它非常简单。

相关文章: