在二维矢量中查找非支配点

Finding non-dominated points in 2D vector

本文关键字:查找 二维      更新时间:2023-10-16

我必须在n-校正空间中生成100个随机点(为了更好地理解这个程序,我将设置二维,所以1个点有2个坐标),并找到非支配点。什么是非支配点?如果我们有点(x0,y0),...,(x99,y99),则如果xi<xjyi<yj,则对i由对j支配。为了找到非支配点,我们可以将它们相互比较(不比较相同的点)。

所以我想创建两个2D向量,将相同的点(pointstemp)存储在它们中,并将它们相互比较,如果当前检查的点不是由所有其他点控制的,则将其放入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算法。

使用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>替换为自己的类。