我是一名 C++ 初学者,我一直在开发一个项目,在该项目中,您必须输入一些用空格分隔的整数,并且程序必须输出所有可能的整数排列。我知道在 python 中,这可以使用[int(item) for item in input().split()]
,但我不知道如何在 C++ 中做同样的事情。我想使用 C++ 中内置的简单方法。有人可以提供一些意见吗?任何帮助将不胜感激。
您会看到,您从字符串创建一个整数向量,然后简单地排列该向量:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string str;
std::getline(std::cin, str);
std::istringstream iss(str);
std::vector<int> vec;
int temp = 0;
while (iss >> temp) {
vec.push_back(temp);
}
//you now have a vector of integers
std::sort(vec.begin(), vec.end()); //this is a must as `std::permutations()` stops when the container is lexicographically sorted
do {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>{std::cout, " "});
std::cout << "\n";
} while (std::next_permutation(vec.begin(), vec.end()));
return 0;
}
要了解如何输出所有可能长度的所有排列,请查看
如何使用 STL 在 C++ 中创建小于总长度的位数的排列 https://stackoverflow.com/questions/61392431/how-to-create-a-permutation-in-c-using-stl-for-number-of-places-lower-than-the
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)