你好我知道有一些类似的问题,但我一直无法解决我的问题。 我需要在笛卡尔坐标上生成一个球体上唯一的一组点,即从球面到笛卡尔的转换。当我这样做时,我将这些点存储在向量中。然而,一些重复被创建并删除它们我尝试过使用排序擦除和独特的功能。问题是这种排序看不到排序我的整个向量,我不明白为什么?它可以很好地处理向量,我只是将数字推回,而不是由我的笛卡尔函数生成的向量向量。我知道这很简单,我已经坚持了3天,我确信它正在凝视我的脸!代码和输出均低于排序和删除重复从载体<矢量< double>>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stdio.h>
int main(int argc, const char * argv[]){
std::vector<double> locations; //center of the bubble
locations.push_back(1.0);
locations.push_back(1.0);
locations.push_back(1.0);
std::vector<std::vector<double> > points; //set of points to be created around the bubble
double PI=atan(1)*4;
for(int dr=1; dr<2; dr++){
for (int phi=0; phi<180; phi+=90){
for (int theta=0; theta<360; theta+=90){
std::vector<double> row;
double x=locations[0]+(dr*sin(theta*(PI/180))*cos(phi*(PI/180)));
double y=locations[1]+(dr*cos(theta*(PI/180)));
double z=locations[2]+(dr*sin(theta*(PI/180))*sin(phi*(PI/180)));
row.push_back(x);
row.push_back(y);
row.push_back(z);
points.push_back(row);
}
}
}
std::sort(points.begin(), points.end()); //sort points
std::cout<<"sorted points \n";
for (int i =0; i<points.size(); i++){
std::cout<<points[i][0]<<" "<<points[i][1]<<" "<<points[i][2]<<"\n";
}
points.erase(std::unique(points.begin(), points.end()), points.end()); //erase duplicates
std::cout<<"duplicates removed \n";
for (int i =0; i<points.size(); i++){
std::cout<< points[i][0]<<" "<<points[i][1]<<" "<<points[i][2]<<"\n";
}
}
输出
sorted points
0 1 1
1 1 0
1 0 1 THIS HASN'T BEEN SORTED CORRECTLY
1 1 2
1 2 1
1 2 1
1 0 1 THIS HASN'T BEEN SORTED CORRECTLY
2 1 1
duplicates removed
0 1 1
1 1 0
1 0 1
1 1 2
1 2 1
1 0 1
2 1 1
是的,浮点比较是一种痛苦。 – chris
'for(int dr = 1; dr <2; dr ++)'你不需要循环。你只需要'const int dr = 1;'。 – timrau
我会建议做一个类/结构封装点的方面。然后你可以重载操作符来进行排序和比较。这会让你更容易看到你正在尝试做什么。 –