c++ - 我可以在这里摆脱嵌套的 for 循环吗?

标签 c++ algorithm

我有一个函数,它接受一个 vector 并通过组合其中的所有元素返回一个 vector 。现在,我有 3 个嵌套的 for 循环,它们创建了一个 3 层深的组合。我希望它看起来更好,并且能够在需要时添加功能以使其达到 4 层深。

如果输入 = ["一", "二", "三"]

3 级输出 = "onetwothree""twoonethree"等等。

std::vector<std::string> generator(std::vector<std::string>& x)
{
    std::vector<std::string> output;
    std::string tmp;
    for (auto i : x) {
        output.push_back(i);
        for (auto j : x) {
            tmp = i + j;
            output.push_back(tmp);
            for (auto k : x) {
                tmp = i + j + k;
                output.push_back(tmp);
            }
        }
    }
    return output;
}

我研究过迭代器,但不知道它是否可行。

最佳答案

如果您正在寻找的是简单地生成字符串 vector x 的所有元素的排列并将这些排列存储到另一个输出 vector 中,这可以通过使用 std::next_permutation 轻松实现。和 std::accumulate :

#include <vector>
#include <string>
#include <numeric>
#include <iostream>
#include <algorithm>

std::vector<std::string> generator(std::vector<std::string> x)
{
    std::vector<std::string> output;
    std::sort(x.begin(), x.end());
    do 
    {
        output.push_back(std::accumulate(x.begin(), x.end(), std::string()));
    } while (std::next_permutation(x.begin(), x.end()));
    return output;
}

int main()
{
    auto v = generator({"one","two","three"});
    for (auto& val : v)
        std::cout << val << "\n";
}    

Live Example

std::accumulate 基本上默认在元素上调用operator +,因此字符串会自动连接。

std::next_permutation 而言,其作用的描述在链接中进行了解释。基本上,您希望从排序序列开始,然后调用 std::next_permutation 来获取元素的下一个排列。

请注意,这与“级别”(如您所说)的数量无关。您可以有一个包含 10 个字符串的 vector ,这会正常工作(假设没有内存限制)。

关于c++ - 我可以在这里摆脱嵌套的 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53892918/

相关文章:

c++ - 寻找合数

java - 解决 QR 拼图的算法

algorithm - 使用二进制搜索查找数组中数字的位置

algorithm - 使用组中项目的总和和数量查找组中的数字

c++ - Quicksort 在对降序-升序数据进行排序时的奇怪行为

c++ - 如何先按值对 std::map 排序,然后按键排序?

c++ - 执行 C++ 程序并使用 Perl 复制 cmd 输出

c++ - 无法存储标准输入状态并在 C++ 中进行比较

复制后访问对象时 C++ 程序崩溃

c++ - 200万以内的所有质数之和