polerto
polerto

Reputation: 1790

Find and update an element in C++11 vector of structs

I have a vector of struct as follows

struct myStruct{
    size_t aID;
    int bID;
    double tobeUpdated;
};

std::vector<myStruct> myVec;

how can I find and update a member of myVec which satisfies aID == someId && bID == otherID in an efficient way in C++11?

Upvotes: 0

Views: 1649

Answers (2)

Neil Kirk
Neil Kirk

Reputation: 21773

Assumes only one to be updated.

// what to search for
size_t aID = 5;
int bID = 7;

find_if(vec.begin(), vec.end(), [aID, bID](const myStruct& obj) { return obj.aID == aID && obj.bID == bID; });

Upvotes: 2

Lochemage
Lochemage

Reputation: 3974

If you want to make it more efficient, it really depends on your usage of the struct and array. If it is possible based on how you use it, then I would store them in an std::map instead. This will allow for easy lookup based on ID's or possibly a combination of ID's. However, if it doesn't actually slow your system down noticeably, then I would say to forgo the optimization and just iterate through each index with that test.

Upvotes: 1

Related Questions