首页 > 解决方案 > 如何查看::concat 2 个不同的范围视图?

问题描述

我正在尝试查看::concat 2 个视图。我不明白什么时候可以,什么时候不能,为什么。任何帮助都会很棒。这个问题听起来很相似,但没有解决我的问题。

我尝试了以下代码

#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges;

int main () {
  // 'string' of spaces   
  auto spaces = view::repeat_n(' ',4);  // 1
  // prints [ , , , ]
  std::cout << spaces  << std::endl;

  // 'string' of letters
  auto letters = view::iota('a', 'a' + 4); // 2
  // prints [a,b,c,d]   
  std::cout << letters  << std::endl;

  // 'string' from concat of letters and spaces   
  auto text = view::concat(letters,spaces); // 3
  // prints [a,b,c,d, , , , ]       
  std::cout << text  << std::endl;

  // 'vector<string>' repeat letters
  auto letter_lines = view::repeat_n(letters,3); // 4a
  // prints [[a,b,c,d],[a,b,c,d],[a,b,c,d]]
  std::cout << letter_lines  << std::endl;

  // 'vector<string>' repeat spaces
  auto space_lines = view::repeat_n(spaces,3);  // 4b
  // prints [[ , , , ],[ , , , ],[ , , ,]] 
  std::cout << space_lines  << std::endl;

  // 'vector<string>' concat 2 repeated letter_lines
  auto multi_letter_lines = view::concat(letter_lines,letter_lines); // 5
  // prints [[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d]]
  std::cout << multi_letter_lines << std::endl;

  // 'vector<string>' from concat of letter_lines, and spaces_lines
  // this doesn't work (well it compiles)
  auto text_lines = view::concat(letter_lines,space_lines);
  // this doesn't compile
  std::cout << text_lines  << std::endl;   //  6 ERROR
  // I expected [[a,b,c,d],[a,b,c,d],[a,b,c,d],[ , , , ],[ , , , ],[ , , , ]]

  // This works
  auto flat_text_lines = view::concat(letter_lines | view::join,
                                      space_lines | view::join); // 7
  // prints [a,b,c,d,a,b,c,d,a,b,c,d, , , , , , , , , , , , ]
  std::cout << flat_text_lines << std::endl;
  // but the structure is lost; it's a 'string', not a 'vector<string>'
}

第 6 行之后的 cout 给出了错误

note:   template argument deduction/substitution failed:
concat.cpp:21:19: note:   cannot convert ‘text_lines’ (type‘ranges::v3::concat_view<ranges::v3::repeat_n_view<ranges::v3::iota_view<char, int>>, ranges::v3::repeat_n_view<ranges::v3::repeat_n_view<char> > >’) to type ‘const ranges::v3::repeat_n_view<char>&’
      std::cout << text_lines  << std::endl;

如果我理解错误,则表示 concat<repeat_n<iota<char>>,repeat_n<repeat_n<char>>>无法转换为repeat_n<char>. 好的,我实际上希望 concat 转换为类似的东西repeat_n<repeat_n<char>>,所以错误是有道理的。

但是我希望第 3 行之后的 cout 会抱怨说 concat<iota<char>,repeat_n<char>>不能转换为repeat_n<char>.

为什么第 3 行有效;它实际上变成了什么类型?我应该怎么做才能让 6 号线正常工作?

标签: c++c++11range-v3

解决方案


推荐阅读