bool xInItems = std::find(items.begin(), items.end(), x) != items.end();
是否有更简洁的方法来检查 x 是否在项目中?这似乎不必要地冗长(重复项目三次),这使得代码的意图有点难以阅读。
比如有没有类似下面的东西:
bool xInItems = boost::contains(items, x);
如果不存在任何更简洁的 boost/STL 算法来检查集合是否包含项目,那么使用辅助函数来启用 contains(items, x)< 是好还是坏的做法?/
?
我是否使用了错误的 STL 容器?即使是 std::set 也会导致 bool xInItems = items.find(x) != items.end();
这看起来仍然很冗长。我是不是想错了?
最佳答案
从头开始编写模板函数并不难。
template<typename T, typename Iterator>
bool contains(Iterator it1, Iterator it2, const T & value)
{
return std::find(it1, it2, value) != it2;
}
template<typename T, typename Container>
bool contains(const Container & c, const T & value)
{
return contains(c.begin(), c.end(), value);
}
您甚至可以为具有自己的 find
函数的容器提供特化,这样它就不会调用 std::find
。
关于C++ 简洁地检查 STL 容器中的项目(例如 vector ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186483/