【问题标题】:C++ template function to check if a vector of contains the value?C ++模板函数检查向量是否包含值?
【发布时间】:2021-11-12 10:38:56
【问题描述】:

我曾计划为所有类型实现一种类似于 FORTRAN 的 INDEX 函数。 这会是一个正确的解决方案吗? ** 在 cmets 之后编辑 **

template <typename T>
bool contains(std::vector<T>& vec, T value){
 if (std::any_of(vec.begin(), vec.end(), [value](T j) { return value == j; }))return true;
 return false;
}

注意 泛型实现的浮点类型比较有一个陷阱!

【问题讨论】:

  • 当您描述所有类型时,您的意思是std::arraystd::vectorC-like array
  • 我打算至少使用基本类型,int、float、double、string,...
  • if (A) return true; else return false; = return A;.
  • 旁白:我会为这个函数使用名称contains。我希望index 返回valuevec 中的位置
  • 你会修改向量吗??? -> 通过 const 引用接受它!

标签: c++ templates


【解决方案1】:

是的,这是一个有效的实现,但是我会以不同的方式编写它

template <std::ranges::input_range R, typename T>
requires std::indirect_binary_predicate<ranges::equal_to, ranges::iterator_t<R>, const T*>
bool index(R&& range, const T & value){
    return std::ranges::find(range, value) != std::ranges::end(range);
}

这适用于任何序列和任何可以与该序列的元素进行相等比较的值。

在 C++11 中没有明确要求的概念,但类似

template <typename R, typename T>
bool index(R&& range, const T& value) {
    using std::begin, std::end;
    return std::find(begin(range), end(range), value) != end(range);
}

【讨论】:

  • 我尝试使用,但失败:std::vectors={"111","222","3333three","four"}; std::string s1="112"; std::cout
  • @MathArt 我在这个答案中使用了 C++20 语法。在 C++11 中类似
  • 可以在这里查看ideone.com/a41coh吗?
  • @MathArt 需要一个 c++20 编译器和#include &lt;algorithm&gt; see here
【解决方案2】:

 如果您的程序的目标是找到正确方法的确定值:

template <typename T>
bool index(std::vector<T>& vec, T value){
  return std::any_of(vec.begin(), vec.end(), [value](T j) { return value == j; });
}

 我的程序与@caleth 的答案没有太大区别,因为它是为了编写一个可以处理各种范围的通用函数,例如std::arraystd::vectorC-like array 或其他,你应该写一个这样的模板:

template <typename iter, typename T>
bool any_index(iter begin, iter end, T value) {
    for (; begin != end; ++begin) {
        if (static_cast<T>(*begin) == value) {
            return true;
        }
    }
    return false;
}

用法:

int main() {

    vector<int> v1{ 4, 3, 2, 1 };    
    vector<string> v2{ "hey", "language", "compiler", "bug" };
    vector<char> v3{ 'a', 'b','c', 'd' };
        
    array<int, 6> c{ {1,2,3,4,5,6} };
    unsigned char buf[5] = {0x11, 0x22, 0x33, 0x44, 0x55};
    
    assert(any_index(begin(v1), end(v1), 4) == true);
    assert(any_index(begin(v2), end(v2), string("compiler")) == true);
    assert(any_index(begin(v3), end(v3), 'd') == true);
    assert(any_index(begin(c), end(c), 5) == true);
    assert(any_index(begin(buf), end(buf), 0x11) == true);
          
    return 0;
}

  完整示例 (godbolt)

【讨论】:

  • 我检查过:vector v0{ 4.1f, 3.f, 2.f, 1.12f }; cout
  • 输出值为 1,因为布尔等效值为 true
猜你喜欢
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 2021-12-03
  • 2012-11-24
  • 2019-03-13
  • 2019-08-10
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多