【发布时间】:2012-11-05 13:54:21
【问题描述】:
我需要将一个用 Python 编写的 sn-p 移植到 C++ 但是那个 sn-p 使用的是 python 中 itertools 的组合。
我真正有兴趣移植到 C++ 的那一行是:
for k in combinations(range(n-i),2*i):
Python 中的range(n-i) 将从0 to (n-i) - 1 生成一个列表
设 n = 16, i = 5
print range(n-i)
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
python 组合将在该列表中生成所有可能的组合。
例如
print list(combinations(range(n-i),2*i))
输出:
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 10), (0, 1, 2, 3, 4, 5, 6, 7, 9, 10), (0, 1, 2, 3, 4, 5, 6, 8, 9, 10), (0, 1, 2, 3, 4, 5, 7, 8, 9, 10), (0, 1, 2, 3, 4, 6, 7, 8, 9, 10), (0, 1, 2, 3, 5, 6, 7, 8, 9, 10), (0, 1, 2, 4, 5, 6, 7, 8, 9, 10), (0, 1, 3, 4, 5, 6, 7, 8, 9, 10), (0, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]我想在 C++ 中使用 std::vector 和 next_permutation 生成类似的输出,但我仍然得到错误的结果。这是我目前的做法:
for(int j = 0; j < n-i; j++) {
temp_vector.push_back(j);
}
那个 sn-p 相当于 Python 中的range(n-i)。
但是下面的sn-p:
do {
myvector.push_back(temp_vector);
} while(next_permutation(temp_vector.begin(),temp_vector.begin()+2*i));
cout<<myvector.size()<<endl;
不等同于 Python 中的combinations(range(n-i),2*i)),我尝试了很多变体,但仍然无法得出我期望的结果。
例如:
设 n = 16 i = 5
Python
>>> print len(list(combinations(range(n-i),2*i)))
11
C++
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> temp_vector;
vector< vector<int> > myvector;
int n = 16, i = 5;
for(int j = 0; j < n - i; j++) {
temp_vector.push_back(j);
}
do {
myvector.push_back(temp_vector);
} while(next_permutation(temp_vector.begin(), temp_vector.begin()+2*i));
cout<<myvector.size()<<endl;
return 0;
}
g++ combinations.cpp
./a.out
3628800
任何指导将不胜感激!非常感谢!
【问题讨论】: