尝试使用数组

时间:2017-02-22 22:49:54

标签: c++ arrays

我有以下数组:
int a[3]={1, 2, 3};
注意:我不知道数组有多少元素。

我想输出

  

123; 132; 213; 231; 312; 321。

但是我不知道数组中有多少位数。同样的数字也不能重复。

2 个答案:

答案 0 :(得分:2)

正如评论所说,听起来你想要std::next_permutation,这里有如何使用它:

int main()
{
    std::vector<int> a{ 1, 2, 3 };

    std::sort(a.begin(), a.end());
    do {
        std::cout << a << "; ";
    } while (std::next_permutation(a.begin(), a.end()));

    return 0;
}

请注意,您需要重载operator<<()

std::ostream& operator<<(std::ostream& s, const std::vector<int>& v)
{
    for (auto&& item : v)
        s << item;
    return s;
}

该程序的输出是

  

123; 132; 213; 231; 312; 321;

你甚至可以做一点实用程序:

void permutations(std::ostream& s, std::vector<int> a)
{
    std::sort(a.begin(), a.end());
    do {
        s << a << "; ";
    } while (std::next_permutation(a.begin(), a.end()));
}

permutations(std::cout, a);
std::cout << "\n";
permutations(std::cout, { 3, 1, 4, 2 });

答案 1 :(得分:0)

所以它的排列。你有N! permuations。

最简单的方法是递归地编写函数,枚举第一个数字,然后是N-1中的第二个数字,N-2中的第三个数字,依此类推。