【问题标题】:C/C++ how to combine multiple arrays/lists of strings?C/C++ 如何组合多个数组/字符串列表?
【发布时间】:2013-08-26 12:15:28
【问题描述】:

我有 5 个包含字符串的列表:追加、单词、中间、组合、前置。 (或 s0、s1、s2、s3、s4)。 每个列表在程序启动时可以随机包含 0 到 256 个字符串。

如何输出所有可能的组合?

我尝试了级联的 for() 循环,但如果中间的列表包含 0 个字符串(例如 s2),则会失败。

【问题讨论】:

  • 使用sprintf,但问题对我来说不是很清楚。
  • 可能它会失败,因为您不处理角落案例。请发布您的代码,以便我们查看您做错了什么。
  • 5 个字符串列表或 5 个字符串列表?
  • 我的第一个问题是为什么?在 256 个字符串的 5 个列表的情况下,您正在查看超过 1 万亿个组合......

标签: c++ c string list combinations


【解决方案1】:

我假设你使用std::vector<string> s1,s2,s3,s4,s5;
如果你喜欢丑陋的代码:

int i = 1;
for (auto itr1 = s1.begin(), end1 = s1.end(); itr1 != end1; ++itr1)
    for (auto itr2 = s2.begin(), end2 = s2.end(); itr2 != end2; ++itr2)
        for (auto itr3 = s3.begin(), end3 = s3.end(); itr3 != end3; ++itr3)
            for (auto itr4 = s4.begin(), end4 = s4.end(); itr4 != end4; ++itr4)
                for (auto itr5 = s5.begin(), end5 = s5.end(); itr5 != end5; ++itr5)
                    std::cout<<"solution "<<i++<< ": "<< *itr1 << " - " << *itr3<< " - " << *itr4<< " - " << *itr5 <<std::endl;

它并不优雅,但在 sX.size()==0 时不会失败。

希望对你有帮助!

【讨论】:

    【解决方案2】:

    为什么不放一个 if 来检查列表是否为空?

    【讨论】:

      【解决方案3】:

      我假设您的示例要排列数组中的单词

      由于 C++ 被标记,我更喜欢关注(使用 vectorstring

      #include <algorithm>
      #include <string>
      #include <iostream>
      #include <vector>
      #include <iterator>
      
      int main()
      {
      
          std::vector <std::string> v ={ "append", "word", 
                             "middle", "combo", "prepend"};
      
          //Use v.push_back to add any number of strings
      
          std::sort(v.begin(), v.end());
          do {
              std::copy(v.begin(), v.end(), 
                        std::ostream_iterator<std::string>(std::cout, " "));
              std::cout<<std::endl;
          } while(std::next_permutation(v.begin(), v.end()));
      }
      

      我很确定你已经知道对于 256 字符串你会等到 256!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-06
        • 2017-06-26
        • 2011-08-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        相关资源
        最近更新 更多