C++ 简洁地检查 STL 容器中的项目(例如 vector )

标签 c++ boost stl

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/

相关文章:

c++ - 如何通过 boost asio 向客户端发送 OpenNI 深度图?

c++ - C 预处理器宏 : check if token was declared

c++ - C++ STL 中的 erase() 实际上删除了元素吗?

C++ 模板化生产者-消费者 BlockingQueue,无界缓冲区 : How do I end elegantly?

c++ - 查找全局变量而不是在 C++ 函数中构造它们

c++ - 确定 c/c++ 代码中内存泄漏的工具

c++ - 限制文件流的文件大小?

c++ - 库文件结构的常见做法

c++ - 是否可以检查 boost::lockfree::queue 是否已满?

c++ - 我可以在 C++ 的映射结构中使用 vector 作为索引吗?