c++ - (C++) 用于检查对象是否在 vector/数组/列表/...中的模板?

标签 c++ arrays c++11 vector stl

是否可以在 C++(11) 中为函数创建模板以检查对象是否包含在 std::vectorstd::arraystd::list(可能还有更多容器类型)?

我现在拥有的:

typedef std::shared_ptr<Tag> SharedTag;
typedef std::vector<SharedTag> TagList;

bool
Tag::isIn(const TagList& lst) {
    return std::any_of(lst.begin(), lst.end(), [this](const SharedTag& t) {
        return t->name == this->name;
    });
}

标签 是一个普通的。当然,比较应该是 t == this,稍后将是一个 operator==。为简单起见,我没有在此处包含此内容。

那么,是否可以只为 std::vectorstd::array 编写一次上层代码(尽管没有 typedef) std::list(, maybe for std::set) 等等?

我找不到所有这些类的基类型,...这是我的第一个想法...

最佳答案

选项 1(好):只需使用 std::find直接:

std::vector<int> v; // populate v however you want
std::vector<int>::const_iterator i = std::find(v.cbegin(), v.cend(), 42);
if (i != v.end()) {
    // Now you know 42 is in v
} else {
    // Now you know 42 is not in v
}

选项 2(更好):将 std::find 包装在辅助函数中:

template <typename Container, typename Value>
bool contains(const Container& c, const Value& v)
{
    return std::find(std::begin(c), std::end(c), v) != std::begin(c);
}

// Example usage:
std::vector<int> v; // populate v however you want
if (contains(v, 42)) {
    // You now know v contains 42
}

选项 3(最佳):使用提供一个容器的 find 方法(这对于排序的容器更快,如 set)和 std: :find 对于不提供容器的容器:

// If you want to know why I added the int and long parameter,
// see this answer here: http://stackoverflow.com/a/9154394/1287251

template <typename Container, typename Value>
inline auto contains(const Container& c, const Value& v, int) -> decltype(c.find(v), bool()) {
    return c.find(v) != std::end(c);
}

template <typename Container, typename Value>
inline bool contains(const Container& c, const Value& v, long) {
    return std::find(std::begin(c), std::end(c), v) != std::end(c);
}

template <typename Container, typename Value>
bool contains(const Container& c, const Value& v) {
    return contains(c, v, 0);
}

// Example usage:
std::set<int> s; // populate s however you want
if (contains(s, 42)) {
    // You now know s contains 42
}

当然,您可以自己编写 std::find,但您也可以使用它。

关于c++ - (C++) 用于检查对象是否在 vector/数组/列表/...中的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705742/

相关文章:

c++ - 将自定义大小的多维数组传递给函数

c++ - 我如何静态编译 libstdc++11?

c++ - 并非针对所有未使用的静态常量变量都引发未使用变量警告

python - 无法使用 python ctypes 加载 C++ 共享库

c++ - 将任何函数作为模板参数传递?

C++ 获取网格中单元格的邻居,-1x 在检查时抛出 null 异常!= NULL

c++ - clang 的行为不同于 msvc++ 和 gcc

java - 调用方法时出现问题(扫雷)

C++ NULL 指针和 const 正确性

C++显示在txt文件中找到的唯一日期及其相关价格