C 生成列表的不同排列

C++ generating different permutations of a list?

本文关键字:排列 列表      更新时间:2023-10-16

嗨,我正在为C 做一个作业,不幸的是,我的老师无法教我有关C 的任何东西,因此我必须求助于互联网以帮助我。

我会感谢一种简单,简单的方法来输出列表的所有排列,例如,如果列表x具有[1,2,3]的3个不同值,则输出= [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]等...该列表不一定具有为了按此顺序,只需在列表中输出1、2、3的所有不同组合即可。就这样。我在网上浏览了如何弄清楚如何做到这一点,没有太多运气的了解。我已经看到人们为此使用向量,还有很多我对0%的理解的其他事物。我很想复制并粘贴他人的代码,但这无济于事,因为我是唯一一个自愿学习这种语言的C 的任何地方。因此,请尝试尽可能多地用外行的术语来解释它。如果有帮助,我正在使用C 11。

这是我自己的

std::cout << "nPart 2: Enter a list of 3 numbers, press enter after each value: n";
std::list<int> mylist1;
int v1;
int v2;
int v3;
std::cin >> v1 >> v2 >> v3; //input that will go into the list
mylist1.push_front(v1);
mylist1.push_back(v2);
mylist1.push_back(v3);

有一个函数,称为 next_permutation

#include <algorithm>
#include <vector>
#include <iostream>
void show(const std::vector<int> &vtr) {
    for (auto val : vtr)  std::cout << val << " ";
    std::cout << "n";
}
int main() {
    std::vector<int> vec{ 12,1,6,4,0 };
    std::sort(vec.begin(), vec.end());
    show(vec);
    while (std::next_permutation(vec.begin(), vec.end())) {
        show(vec);
    }
}