![](/img/trans.png)
[英]What is the computationally efficient way to merge two associated std::stack into a std::map in C++
[英]C++ efficient way to find matches between two std::map
我有一個使用RGB-D相機獲取的數據集和一個文本文件,其中為該數據集的每個圖像存儲了時間戳和文件名。 我要做的是解析此文件並填充兩個std :: map,一個用於rgb圖像,另一個用於深度圖像。 現在,由於時間戳不相交,因此我必須編寫一個例程來根據時間戳查找匹配的圖像。 這是我到目前為止寫的:
typedef map<double,string> StampImageMap;
...
vector<string> &vstrImageFilenamesRGB;
vector<string> &vstrImageFilenamesD;
vector<double> &vTimestampsRGB;
vector<double> &vTimestampsDPT;
double tolerance = 0.02;
for(StampImageMap::iterator it=rgb_images.begin(); it != rgb_images.end(); it++) {
bool found = false;
StampImageMap::iterator jt=depth_images.begin();
while(found == false && jt!=depth_images.end()) {
if(fabs(it->first - jt->first) < tolerance) {
found = true;
vstrImageFilenamesRGB.push_back(it->second);
vstrImageFilenamesD.push_back(jt->second);
vTimestampsRGB.push_back(it->first);
vTimestampsDPT.push_back(jt->first);
}
jt++;
}
}
我想知道是否有更有效的方法來執行此任務!
現在編寫代碼時,復雜度為Θ(nm) ,其中n , m是序列的大小。 至少有兩種方法可以改善此問題(第二種方法效率更高,但更難編寫代碼)。
在外部循環的主體中,不要通過while(found == false && jt!=depth_images.end())
第二張地圖中的所有元素。 而是使用std::map::lower_bound
和std::map::upper_bound
分別搜索it->first - tolerance
和it->first + tolerance
。 僅在這兩個調用的結果之間循環。
因此,代碼變成了這樣的東西:
for(StampImageMap::iterator it=rgb_images.begin(); it != rgb_images.end(); it++) { StampImageMap::const_iterator lower = depth_images.lower_bound(it->first - tolerance); StampImageMap::const_iterator upper = depth_images.lower_bound(it->first + tolerance); // Now just search between lower and upper. }
這會將每次迭代減少到Θ(log(m))+ p ,其中p是此范圍的大小。
由於地圖的鍵是已排序的,因此您可以修改一種標准方法,以查找這種情況下兩個已排序數組的交集 。 這會將運行時間縮短至Θ(m + n) 。 請注意,該修改有些棘手,因為您不是要查找精確元素的交集,而是要找到“足夠接近”的元素的交集。
這是這種情況的偽代碼 :
it = rgb_image.begin(); jt = depth_image.begin(); while(it != rgb_image.end() && jt != depth_image.end()) { if(fabs(it->first - jt->first) < tolerance) { // Match found! ++it; ++jt; continue; } if(it.first > jt.first + tolerance) { ++jt; continue; } ++it; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.