[英]Sorting two vectors at once?
我當前的項目涉及根據點到xy坐標平面原點的距離對點進行排序。 它必須找到每個點到原點的距離,對距離進行排序,然后輸出創建距離的點,而不是距離。 它只能使用bucketsort和vector。 我的排序工作正常,但是我很難弄清楚如何確保距離向量和點向量保持對齊。 (即使該點最初不在C [0]處,也已從c [0]處的點創建了一個B [0]的距離。)這是到目前為止的代碼。
以標准用戶輸入為例:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2
首先,主要是從用戶那里獲取輸入。 該點的每一半最初都作為其自身的對偶放入向量A中,然后在向量C中與另一半結合為一對。
int main(){
double number; int t = 0; pair<double,double> x;
while (cin >> number){
A.push_back(number); }
while (t < A.size()){
x = make_pair(A[t], A[t+1]); C.push_back(x); t += 2; }
int q = 0;
while (q < (C.size() - 1)){
findDistance(C[q].first, C[q].second);
q++;
}
然后,使用距離函數找到所有距離,並將結果存儲在向量B中。這是該函數。
void findDistance(double x = 0, double y = 0) {
double x2 = pow(x, 2);
double y2 = pow(y, 2);
double z = x2 + y2;
double final = sqrt(z);
B.push_back(final);
}
桶分類會組織所有距離,並將結果靜態存儲在B中。
void bucketSort(vector<double> &arr)
{
int n = B.size();
vector<double> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
問題就在這里。 B已排序,但C保持其原始順序。 瀏覽表之間的值並進行比較以找到正確的順序是非常昂貴的。 (參數之一是將運行時間保持為O(n)。關於如何解決此問題是否有任何想法?
這是我完整的代碼:
vector<double> A;
vector<double> B;
vector<pair<double,double>> C;
void findDistance(double x = 0, double y = 0) {
double x2 = pow(x, 2);
double y2 = pow(y, 2);
double z = x2 + y2;
double final = sqrt(z);
B.push_back(final);
}
void bucketSort(vector<double> &arr)
{
int n = B.size();
vector<double> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
int main(){
double number; int t = 0; pair<double,double> x;
while (cin >> number){
A.push_back(number); }
while (t < A.size()){
x = make_pair(A[t], A[t+1]); C.push_back(x); t += 2; }
cout << setprecision(5); cout << fixed;
int q = 0; double r = 0; double d = 0;
while (q < (C.size() - 1)){
findDistance(C[q].first, C[q].second);
q++;
}
bucketSort(B);
cout << showpos; cout << fixed;
//more cout here to show results
}
這是輸入和輸出的示例:輸入:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2
輸出:
-0.380000 +0.200000
+0.200000 +0.380000
-0.300000 +0.410000
+0.651600 -0.100000
任何幫助將不勝感激,請謝謝。
首先,我認為您應該決定是否真的需要知道距離,或者只需要對點向量進行排序。 如果您不需要它們,則無需單獨存儲它們。 我要做的是:
實現像double get_distance()
這樣的成員函數也可能很有用。 同樣,如果您打算多次獲得該獎勵,則成員double distance
可能會很有用。
或者,您可以為pair<double,double>
元素定義比較函數,並在排序期間將其用作Compare函數。
希望我寫的東西有意義。
在這種情況下,一個常見的技巧是首先對一個輔助向量進行排序,該向量包含您真正要排序的向量的索引。 就是說,對vector<size_t> H
排序不是i<j
而是B[i] < B[j]
。
然后,創建Bnew[i] = B[H[i]]
和Cnew[i] = C[H[i]]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.