Search C ++ std vector structs for struct with matching string

I'm sure I'm making it harder than it should be.

I have a vector ...

vector<Joints> mJointsVector; 

... consisting of structures structured after the following:

 struct Joints { string name; float origUpperLimit; float origLowerLimit; }; 

I'm trying to search mJointsVector with "std :: find" to find a single joint by its string name - so far no luck, but the examples from the ones below have helped, at least conceptually:

Vectors, structures, and std :: find

Can someone point me further in the right direction?

+7
c ++ find data-structures vector std
source share
6 answers

Direct approach:

 struct FindByName { const std::string name; FindByName(const std::string& name) : name(name) {} bool operator()(const Joints& j) const { return j.name == name; } }; std::vector<Joints>::iterator it = std::find_if(m_jointsVector.begin(), m_jointsVector.end(), FindByName("foo")); if(it != m_jointsVector.end()) { // ... } 

Alternatively, you may need to look at Boost.Bind to reduce the amount of code.

+16
source share

What about:

 std::string name = "xxx"; std::find_if(mJointsVector.begin(), mJointsVector.end(), [&s = name](const Joints& j) -> bool { return s == j.name; }); 
+5
source share

You should be able to add an equality operator for your structure.

 struct Joints { std::string name; bool operator==(const std::string & str) { return name == str; } }; 

Then you can search with find.

+1
source share
 #include <boost/bind.hpp> std::vector<Joints>::iterator it; it = std::find_if(mJointsVector.begin(), mJointsVector.end(), boost::bind(&Joints::name, _1) == name_to_find); 
+1
source share
 bool operator == (const Joints& joints, const std::string& name) { return joints.name == name; } std::find(mJointsVector.begin(), mJointsVector.end(), std::string("foo")); 
0
source share
 struct Compare: public unary_function <const string&> { public: Compare(string _findString):mfindString(_findString){} bool operator () (string _currString) { return _currString == mfindString ; } private: string mfindString ; } std::find_if(mJointsVector.begin(), mJointsVector.end(), Compare("urstring")) ; 
0
source share

All Articles