【问题标题】:How to iterate over few containers in sequence? [duplicate]如何按顺序迭代几个容器? [复制]
【发布时间】:2017-05-26 13:16:55
【问题描述】:

具有与以下类似的代码:

#include <iostream>
#include <vector>

int main()
{
  std::vector<std::string> v1, v2;
  for (const auto& s : v1) {
    // do something with s
  }
  for (const auto& s : v2) {
    // do something with s
  }
}

我想一次性遍历v1v2 中的所有元素(由于这些循环中的逻辑有点困难,我不能在其中使用函数——为了这个问题)。

所以理想的解决方案是这样的:

  for (const auto& s : magic(v1,v2)) {
    // do something with s
  }

显然没有分配所有复制到其中的元素的新容器(因为该解决方案是微不足道的。

有什么类似的吗?在boost?

【问题讨论】:

标签: c++ loops boost iterator containers


【解决方案1】:

range-v3,你可以这样做

const std::vector<std::string> v1{"A", "B", "C"}, v2{"D", "E", "F"};

for (const auto& s : ranges::view::concat(v1, v2)) {
    std::cout << s << std::endl;   
}

Demo

【讨论】:

【解决方案2】:

这是一个使用higher-order function 的解决方案:

template <typename TC0, typename TC1, typename TF>
void forJoined(TC0&& c0, TC1&& c1, TF&& f)
{
    for(auto&& x : c0) f(x);
    for(auto&& x : c1) f(x);
}

您可以按如下方式使用forJoined

std::vector<int> a{0, 1, 2};
std::vector<char> b{'a', 'b', 'c'};

forJoined(a, b, [](auto x){ std::cout << x; });
// Will print "012abc".

正如您所见,forJoined 在您的容器存储不同类型的元素时也可以使用。使用模板参数传递f 不会引入额外开销(see my latest article on the subject)

您可以使用variadic template 将其扩展到任意数量的容器。

【讨论】:

    【解决方案3】:

    您可以使用初始化列表。例如

    #include <iostream>
    #include <vector>
    #include <string>
    #include <functional>
    #include <initializer_list>
    #include <functional>
    
    int main() 
    {
        std::vector<std::string> v1 = { "A", "B", "C" };
        std::vector<std::string> v2 = { "X", "Y", "Z" };
    
        for ( const auto &r : { std::cref( v1 ), std::cref( v2 ) } )
        {
            for ( const auto &s : r.get() ) std::cout << s << ' ';
        }
    
        std::cout << std::endl;
    
        return 0;
    }
    

    程序输出是

    A B C X Y Z 
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2019-01-30
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多