簡體   English   中英

在向量中找到最小的數字

[英]Finding the smallest number in vector

給定一個包含5000+個元素(距離)的向量,確定最小非零值的最快方法是什么? 目前,我有些天真:

double distance=1E10; //I know that my distances are always less than this
for (unsigned int i=0; i< a.size(); i++){
  if (a.at(i) < distance && a.at(i) != 0){
    distance=a.at(i);
  }
} 

我考慮過先對向量排序,然后再獲取第一個非零值,但我希望有人可以提供一種更快的優化方法。

auto min = std::numeric_limits<double>::max();
for(auto& v : a) {
    if(v < min && v != 0) {
        min = v;
    }
}

非常簡單。 如果您可以保持排序的集合,那么您可以比O(n)做得更好。 您當前多次使用.at() ,它執行邊界檢查。

為此的標准功能:

auto min = *std::min_element(begin(distances), end(distances),
    [](double a, double b) { return b==0 || a<b; } );

一些簡單但非常快的方法。

double best=1E10; //I know that my distances are always less than this
for (unsigned int i=0; i< a.size(); i++){
  if (a[i] < best && a[i] != 0){
    best=a[i];
  }
}

double best=1E10; //I know that my distances are always less than this
for (auto it = a.begin(); it!= a.end(); ++it){
  if (*it < best && *it != 0){
    best=*it;
  }
}

您可以嘗試使用std::sortstd::upper

std::sort(vec.begin(), vec.end());
auto upper = std::upper(vec.begin(), vec.end(), 0.0);
std::cout << *upper;

您為什么要在該向量中線性搜索? 這是最壞的情況。 只需向量進行排序 ,然后找到最小值即可。 是不是很簡單? 檢查代碼:

假設,

vector <int> v; // it contains values 5,4,1,2,3
sort(v.begin(),v.end()); //STL sort function

那么v [0]是最小值= 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM