c + +简明检查,如果在STL容器项(例如向量) [英] C++ concisely checking if item in STL container (e.g. vector)

查看:111
本文介绍了c + +简明检查,如果在STL容器项(例如向量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool xInItems = std::find(items.begin(), items.end(), x) != items.end();

有没有检查,如果x是项目的更简洁的方法吗?这似乎是不必要的冗长(项重复三次),这使得code稍微用力阅读的意图。

Is there a more concise way of checking if x is in items? This seems unnecessarily verbose (repeating items three times), which makes the intent of the code a little harder to read.

例如,是否有类似如下:

For example, is there something like the following:

bool xInItems = boost::contains(items, x);

如果不存在任何更简洁升压/ STL算法来检查,如果一个集合包含项目,是它认为好或不好的做法,改为使用辅助函数,使包含(物品, X)

If there doesn't exist any more concise boost/stl algorithm to check if a collection contains an item, is it considered good or bad practice to use instead a helper function to enable contains(items, x)?

我使用了错误的STL容器?即使是一个std ::组将导致布尔xInItems = items.find(X)= i​​tems.end(!); 这似乎仍然冗长。我在思考这个错误的方式?

Am I using the wrong STL container? Even a std::set would result in bool xInItems = items.find(x) != items.end(); which still seems verbose. Am I thinking about this the wrong way?

推荐答案

如果的数据进行排序,你可以使用的std :: binary_search ,它返回一个布尔

If your data is sorted, you can use std::binary_search, which returns a bool:

bool xInItems = std::binary_search(items.begin(), items.end(), x));

如果你真的需要保留的项目未排序,但C ++ 11可用,你可以使用的std :: any_of ,但它需要一个predicate,所以它很可能至少冗长的结束的std ::找到(甚至更多的话)。

If you really need to leave the items un-sorted, but have C++11 available, you could use std::any_of, but it requires a predicate, so it's likely to end up at least as verbose as std::find (and probably more so).

这篇关于c + +简明检查,如果在STL容器项(例如向量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆