I'm using a vector for several arrays in my code due to the 开发者_开发百科requirement of random access to the individual elements of the array. Some user GUI operations require searching through the array (but not enough to warrant the use of std::map
), so littered through the code is this:
if (std::find(array.begin(), array.end(), searchfor) != array.end()) { ... }
I'm thinking of a better and more easily readable way of doing this, perhaps creating a method so I can do something like if (array_find(searchfor) != array.end())
or maybe even extending vector so I can do if (array.find(searchfor) != array.end())
.
I'm not sure of the best way to do it. Any ideas?
Use whatever you prefer. I believe doing a function is better though, it avoids the hassle of creating a new class and using it everywhere. Something like :
bool array_contains(searchFor)
{
return std::find(array.begin(), array.end(), searchfor) != array.end();
}
You might find Boost.Range worth a look. Basically you can get rid of begin/end calls as arguments, using collection reference instead.
#include <boost/range/algorithm/find.hpp>
...
if (boost::find(array, searchfor) != array.end()) { ... }
The advantage of this solution is that you still get iterator as a result, which often proves to be useful.
Unless you want to re-write the entire Standard library to use ranges in cases where it's appropriate (like this one) and ensure that everyone that you work with also does this, then the first posted code is the best one.
精彩评论