我必须在n维空间中生成100个随机点(对于此程序,我将设置2维以更好地理解-因此1点具有2个坐标)并找到非控制点。什么是非支配点?如果我们有点(x0,y0),...,(x99,y99)
,则如果i
和j
对xi<xj
对yi<yj
是主导的。要查找非支配点,我们可以将它们相互比较(而无需比较相同点)。
因此,我想创建两个2D向量以将两个相同的点(points
和temp
)存储在两个向量中,将它们彼此进行比较,如果当前检查的点不是所有点都占主导地位其他-将其放入nondominated
容器中。问题是我不怎么比较它们。
这是一小段代码:
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <numeric>
using namespace std;
double genRand() {
double temp = (double)rand() / RAND_MAX * 100.0 - 50.0;
return temp;
}
void fill_row(vector<double> & row) {
generate(row.begin(), row.end(), genRand);
}
void fill_matrix(vector<vector<double>> & matrix) {
for_each(matrix.begin(), matrix.end(), fill_row);
}
int main()
{
srand(time(NULL));
vector<vector<double>> points(100, vector<double>(2));
vector<vector<double>> temp(100, vector<double>(2));
vector<vector<double>> nondominated;
fill_matrix(points);
copy(points.begin(), points.end(), temp.begin());
return 0;
}
注意:我不能在此程序中使用任何循环-只能使用STL算法。
答案 0 :(得分:0)
使用remove_if:
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <numeric>
using namespace std;
vector< pair<double,double> > points(100);
double genRand()
{
double temp = (double)rand() / RAND_MAX * 100.0 - 50.0;
return temp;
}
void fill_row(pair<double,double> & row)
{
row.first = genRand();
row.second = genRand();
}
void fill_matrix(vector< pair<double,double> > & matrix)
{
for_each(matrix.begin(), matrix.end(), fill_row);
}
bool IsDominated( pair<double,double>& testpoint )
{
// check if test point is dominated by any other point
if ( any_of(points.begin(), points.end(), [ testpoint ](pair<double,double>& ip )
{
// is the test point dominated by iterated point
// both x and y must be greated in order to dominate
return ( ip.first > testpoint.first && ip.second > testpoint.second );
}) )
return true;
// no other points dominated
return false;
}
int main()
{
srand(time(NULL));
// generate some random points
fill_matrix(points);
// display points
for_each( points.begin(), points.end(), []( pair<double,double>& ip )
{
cout << ip.first <<","<< ip.second <<" ";
});
cout << "\n";
// remove the dominated points
auto pend = remove_if(points.begin(), points.end(), IsDominated );
pend--;
std::cout << "\nUndominated points:\n";
for_each( points.begin(), pend, []( pair<double,double>& ip )
{
cout << ip.first <<","<< ip.second <<" ";
});
return 0;
}
对于n个维度,您将必须用自己的类替换pair<double,double>
。