惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
G
Google Developers Blog
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
J
Java Code Geeks
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
IT之家
IT之家
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
Google DeepMind News
Google DeepMind News
小众软件
小众软件
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
B
Blog

Jia Yue Hua

完美转发不完美 闲散颂 adapting c++20 ranges algorithms for most metaprogramming Reproducible github Developer Environments 使用mpmcpipeline和jthread实现软流水 在其它线程周期回调函数 在当前线程周期回调函数 cpo和tag_invoke transparent,为关联容器增加查找成员
for_each
Jia Yue Hua · 2023-05-20 · via Jia Yue Hua

C++11引入了range for loop,可是range for loop只能拿到向前range的元素,而没法取得循环的当前下标。

folly提供了for_each算法,相比标准库的for_each,folly的for_each回调的函数对象或函数可接受两个参数,这时第一个指当前元素,第二个值循环的下标。同时folly的for_each还可对异构的tuple操作。此外folly for_each还可支持提前结束操作,类似for循环的break。

例子:

#include <gtest/gtest.h>
#include <folly/container/Foreach.h>
#include <type_traits>
#include <tuple>
#include <vector>
#include <fmt/format.h>
TEST(for_each, foreach)
{
  auto v = std::vector {1,2,3};
  auto t = std::make_tuple (1,2,3);
  auto tb = std::make_tuple (1,2,3.2);
  auto func = [](auto elem,auto index){
    fmt::print("elem:{}, index: {}\n", elem,index);
    if (elem == 2)
    {
      return folly::loop_break;
    }
    return folly::loop_continue;
  };
  auto funcb = [](auto elem){
    fmt::print("elem:{}\n", elem);
    if (elem == 2)
    {
      return folly::loop_break;
    }
    return folly::loop_continue;
  };
  folly::for_each (v,func);
    fmt::print("++++++\n");
  folly::for_each (t,func);
    fmt::print("++++++\n");
  folly::for_each (tb,func);
    fmt::print("++++++\n");
  folly::for_each (tb,funcb);
    fmt::print("++++++\n");

}

Posted 2023-05-20