通过使用structure的元素来获取一个结构数组

Getting an array of structures by using an element of structure

本文关键字:一个 数组 结构 获取 structure 元素      更新时间:2023-10-16

我有一个数组,它包含如下结构:

struct Point
{
int x;
int y;
}
Point array_of_structure[10] ;
for(int i=0;i<10;i++)
{
  array_of_structure[i].x = i*2;
}

我想得到x值为6的结构。通过这种方式,我可以访问该结构的y值。我该怎么做?它类似于以下内容:

Point p = Get the structure which contains x value of 6;
int c = p.y;

这是一个溶液样本。但我需要一个或多个更好的主意。

for(int i=0;i<10;i++)
   if(array_of_structure[i].x==6)
      return array_of_structure[i].y;

我想也许指针能胜任这份工作,但我不确定。我不知道如何解决这个问题。

标准库提供了一个函数std::find_if,该函数可用于查找不带循环的项。然而,作为一个学习练习,你可以使用如下所述的循环:

您可以迭代struct的数组,直到找到感兴趣的x。根据您的偏好,您可以使用指针或索引。你需要设置一个标志,指示你是否找到了你的物品。

以下是使用指针的方法:

struct Point *ptr;
bool found = false;
for (ptr = array_of_structure ; !found && ptr != &array_of_structure[10] ; ptr++) {
    found = (ptr->x == x);
}
if (found) {
    cout << ptr->y << endl;
}

以下是使用索引的方法:

int index ;
bool found = false;
for (index = 0 ; !found && index != 10 ; index++) {
    found = (array_of_structure[index].x == x);
}
if (found) {
    cout << array_of_structure[index].y << endl;
}

注意:如果您正在寻找find_if解决方案,这里有一个解释这种方法的答案。

相关文章: