Reputation: 407
I have a vector of structs Data
which has an integer data member ID
. I need to search if it contains an instance of a specific ID. I had to do it this way:
int DataSize = 0;
for(unsigned count = 0; count < Data.size(); count++)
{
if(ID == Data[count].ID)
DataSize++;
}
Where ID
is previously defined. Any more efficient way to search a vector of objects ? Especially when it is a part of an embedded application.
Upvotes: 0
Views: 221
Reputation: 4432
With C++11 and lambdas could write a little more expresive as:
If you want to count the struct with ID:
std::count_if(std::cbegin(dataArray), std::cend(dataArray), [ID](const Data& data) {
return data.ID == ID;
});
If you want to known if there is at least one:
bool found_ID = std::cend(dataArray) != std::find_if(std::cbegin(dataArray), std::cend(dataArray), [ID](const Data& data) {
return data.ID == ID;
});
The other algorithms of the STD it's always good to have at hand, some are used only very few time, but could save a lot of debugging (with edge case) and performance problems if implemented by hand.
Upvotes: 1
Reputation: 16737
Use std::count_if
.
std::count_if(Data.begin(), Data.end(), [&ID](const DataType& data){return ID == data.ID; };
where DataType
is the type of elements contained in Data
.
Note that there are no real efficiency gains to be had unless Data
satisfied some more conditions, for example, being sorted by ID
. However, using a standard algorithm improves readability.
Upvotes: 1