You can use the standard algorithm std::find_if
. For example
#include <vector>
#include <iterator>
#include <algorithm>
//…
int id = some_value;
auto it = std::find_if( std::begin( all_data ), std::end( all_data ),
[=]( const Staock &stocl )
{
return stock.id == id;
} );
if ( it != std::end( all_data ) )
{
std::cout << it->id << '\n';
}
Instead of the lambda you could use the function object std::equal_to
and std::bind
provided that you are going to compare the whole objects of the type Stock or if you will declare a corresponding comparison operator.
Here is a demonstrative program that uses a lambda
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
struct Stock{
int id;
std::string title;
std::string colour;
std::string size;
int quantity;
float cost;
};
int main()
{
std::vector<Stock> all_data =
{
{ 1, "A" }, { 2, "B" }, { 3, "C" }, { 4, "D" }, { 5, "E" }
};
int id = 3;
auto it = std::find_if( std::begin( all_data ), std::end( all_data ),
[=]( const Stock &stock )
{
return stock.id == id;
} );
if ( it != std::end( all_data ))
{
std::cout << it->id << ": " << it->title << '\n';
}
return 0;
}
Its output is
3: C