0

I am a beginner in c++ and need a simple way to search for a specific struct element within a vector using a unique ID.

e.g. i have the following:

typedef struct {
    long unsigned int id;
    int var1;
    int var2;
    float result;
}struct_t;

vector <struct_t> strct;

now how can i search for a specific id using std::find_if on the vector struct and get a pointer to the struct?

aren't there constructs like:

struct_t*p_struct = find_if(strct.begin(),strct.end(), {strct.id == 21}  );
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
rennreh
  • 11
  • 1
  • 2
    Which C++ textbook you're using that taught you to write "typedef struct"? This is C, not C++. Whatever textbook you're using is horribly out of date and is not teaching you modern, proper, C++. You should replace it with [a more up to date C++ textbook, instead](https://stackoverflow.com/questions/388242/). And each modern C++ textbook would have specific examples of doing exactly what you're asking. These kinds of basic operations are covered in every introductory textbook. Feel free to ask ***specifically*** what's in your textbook's explanation that might be unclear, about this. – Sam Varshavchik Mar 20 '22 at 13:54
  • 3
    The concerns of how you've specified your struct type aside, try reading sensible documentation for `std::find_if()`, such as https://en.cppreference.com/w/cpp/algorithm/find You'll have more luck starting there than by resorting to guesswork, as you have. – Peter Mar 20 '22 at 13:59

1 Answers1

1

The correct syntax to get an iterator to the appropriate element using std::find_if would be as shown below. Here we make use of a lambda as a predicate for the find_if.

#include <iostream>
#include <algorithm>
#include<vector>
struct Info{
    //using in-class initializers for all the built in type data members
    long unsigned int id =0;
    int var1 = 0;
    int var2 = 0;
    float result = 0;
    
};
int main()
{
    std::vector<Info> vec = { {1,2,3,4}, {10,20,30,40}, {100,200,300,400}, {12,22,32,44}};
    
    int findID = 12; //id to be found
    
    auto it = std::find_if(vec.begin(), vec.end(),[findID](const auto& e) { return e.id == findID;});
    
    if(it!=vec.end())
    {
        //do something with the found element using iterator it
        std::cout<<"found"<<std::endl;
        std::cout<<"id: "<<(it->id)<<" var1: "<<(it->var1)<<" var2: "<<(it->var2)<<"result: "<<(it->result)<<std::endl;
    }
    else 
    {
        std::cout<<"not found"<<std::endl;
    }
    return 0;
}

Demo

Jason
  • 36,170
  • 5
  • 26
  • 60