比较两个静态数组
Compare two static arrays
我有一个问题,如何实现比较两个静态数组,即
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()
,直到获得除x
和y
之外的值。
还有其他方法可以做到这一点,但这可能是最容易理解和实现的。
-
数组中的名称彼此对应。所以,如果你需要水果数字i,以并行方式获取bufferNames[i]和bufferPictures[i]。
-
确保名称是平行的。只需制作第二个阵列来自第一阵列元件的元件。
-
对于
0..n-1
范围内的随机,不包括元素编号i,j(j>i),计数为:temp=随机(n-3);k=(温度>=i?温度+1:temp);k=(k>=j?k+1:k);
再拿bufferNames[k]和bufferPictures[k]。
这并不简单,它非常简单。
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- C++两个源文件之间共享的枚举的静态实例
- 如果两个静态库使用相同的另一个静态库,如何避免"LNK2005 Already Defined error"?
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 当我链接两个静态C++库时,我可以在两个主函数库中有两个主要功能吗?
- 静态模板类成员函数的这两个调用之间有什么区别?
- 两个C++库如何共享一个静态缓冲区?
- 如果两个静态库包含 pugixml objs,如何避免与 pugixml 的“已定义”链接错误
- 具有两个动态维度和一个静态维度的多维数组
- 我如何防止静态类成员变量需要两个定义/声明
- 如何链接(或绕过)定义相同符号的两个第三方静态库
- 在两个构造函数之前将我的静态数据成员在 CPP 文件中初始化为 0
- 使用STL交换静态数组中的两个元素
- 两个项目静态地链接同一个SQLite库会导致问题
- 两个使用不同libstdc++版本的静态库
- 为什么使用带有 gcc 和模板函数的两个或多个基于 typedef 的静态断言时会出现"conflicting declaration"错误?
- 如何静态链接到两个版本的 xerces-c(或任何与此相关的库)
- 比较两个静态数组
- 为什么我可以在一个文件中无序地初始化两个静态类变量,而不能初始化三个
- 如何将两个静态库链接到一个Code::Blocks项目