oiyio
oiyio

Reputation: 5935

Getting an array of structures by using an element of structure

I have an array which holds a structure like:

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

I want to get the structure which holds x value of 6. In this way I access the y value of that structure. How can I do it? It's something like the below:

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

Here is a sample solution. But I need a better idea or ideas.

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

I thought about maybe pointers make this job but I'm not sure about it. I cannot figure out how to solve this problem.

Upvotes: 1

Views: 72

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Standard library provides a function std::find_if which can be used to find an item without a loop. As a learning exercise, however, you could do it using a loop as described below:

You can iterate your array of structs until you find the x of interest. You can use a pointer or an index, depending on your preferences. You need to set a flag indicating if you have found your item or not.

Here is how you can do it with a pointer:

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

Here is how you can do it with an index:

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

Note: if you are looking for a find_if solution, here is an answer that explains this approach.

Upvotes: 2

Related Questions