【问题标题】:C++: Find first element of tuple that satisfies predicateC ++:查找满足谓词的元组的第一个元素
【发布时间】:2019-04-20 16:16:47
【问题描述】:

我有以下详细代码:

struct thing1 { int key, std::string value; };
struct thing2 { int key, std::string value; };
// ...
struct thingN { int key, std::string value; };

struct thing_map {
  thing1 t1;
  thing2 t2;
  // ...
  thingN tN;

  std::string get(int key) {
    if(t1.key == key) return t1.value;
    if(t2.key == key) return t2.value;
    // ...
    if(tN.key == key) return tN.value;
    throw std::runtime_error("bad key");
  }
};

我可以将things 重构为std::tuple<thing1, thing2, /* ... */ thingN>,这允许我使用键入的std::get 访问它们,因此不会丢失任何功能(即std::get<thing1>(things))。我不知道如何实现if 级联。有多种函数实现将函数应用于 Internet 上的每个元组元素,但这些函数总是使用索引参数包进行映射,因此我无法选择单个元素并返回其值。要做的微不足道的事情可能是将tN.value 保存到捕获的变量中并返回,但我觉得有更好的解决方案。

为了清楚起见,我想做的是:

struct thing_map {
  std::tuple<thing1, thing2, /* ... */ thingN> things;

  std::string get(int key) {
    foreach(auto&& thing : things) {
      if (key == thing.key) return thing.value;
    }
    throw std::runtime_error("bad key");
  }
};

我正在使用 C++17

【问题讨论】:

  • C++11、C++14 还是 C++17?
  • 既然thingN类型都一样,为什么会有不同的类型?如果它们至少有一个共同的基类,您可以使用它来循环,而不是为每个元素使用不同的不相关类型。
  • 这只是一个人为的例子,不同的东西实际上是不同的。 @max66 C++17,编辑到帖子中。
  • 如果你使用的所有“事物”都有一个共同的关键变量,我真的不明白为什么你不能用关键变量创建一个父类,然后列出指向父类的指针;这样,无论您找到的东西属于哪个子类,您都可以检查键值。
  • @Barnack,你失去了价值语义。在每件事都不同的情况下,您可能还会失去返回确切值类型的能力。这些指针还必须指向存储在某个稳定位置的东西。

标签: c++ templates c++17 stdtuple


【解决方案1】:

你可以使用 C++17 所以我建议使用std::apply() 和模板折叠如下

   std::string get(int key)
    {
      return std::apply([&](auto const & ... args)
       {
         std::string ret;

         ( ((key == args.key) ? (ret = args.value, true) : false)
           || ... || (throw std::runtime_error("bad key"), false) );

         return ret;
       }, things);
    }

以下是完整的编译示例

#include <tuple>
#include <string>
#include <iostream>
#include <stdexcept>

struct thing1 { int key{1}; std::string value{"one"}; };
struct thing2 { int key{2}; std::string value{"two"}; };
struct thing3 { int key{3}; std::string value{"three"}; };
struct thing4 { int key{4}; std::string value{"four"}; };

struct thing_map
 {
   std::tuple<thing1, thing2, thing3, thing4> things;

   std::string get(int key)
    {
      return std::apply([&](auto const & ... args)
       {
         std::string ret;

         ( ((key == args.key) ? (ret = args.value, true) : false)
           || ... || (throw std::runtime_error("bad key"), false) );

         return ret;
       }, things);
    }
 };

int main ()
 {
   thing_map tm;

   std::cout << tm.get(1) << std::endl;
   std::cout << tm.get(2) << std::endl;
   std::cout << tm.get(3) << std::endl;
   std::cout << tm.get(4) << std::endl;
   std::cout << tm.get(5) << std::endl;
 }

【讨论】:

  • 太棒了,谢谢!我很同情任何会读这篇文章的人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
相关资源
最近更新 更多