簡體   English   中英

std :: map迭代器和插入的行為

[英]Behavior of std::map iterators and insertions

作為一個簡單的開始

Map<key,val> map1=//filled up in some way;
Map<key,val> map2;
map2.insert(map1.begin(),map1.end());

我們知道map::insert是O(log(n)),沒有提供提示。 這是否意味着上面的內容在O(nlog(n))中運行,或者它是否使用了map1已經排序並簡單地插入正確位置(遞增當前迭代器)的事實? 因為map1已經排序,我們應該能夠在線性時間內完成。 關於什么

std::copy(map1.begin(),map1.end(),map2.end());

它是每次都插入O(log(n)),還是在O(1)中復制到通過遞增迭代器標記的受尊重位置?

或許更具說明性的例子

template<class InIter, class OutIter, class ResIter>
ResIter foo(InIter first, OutIter last, ResIter res){
   while(first!=last){
      res=*first;
      ++first;
      ++res;
   }
return res;
}

當我們處理地圖迭代器時,這是在O(n)還是O(nlog(n))中運行? 是插入O(log(n)),還是O(1),因為我們指定位置,即*res=*first

為清晰起見編輯:

是否

*res=*first

表現得像

map2.insert(res,*first)

意思是,插入到map2中,使用指向正確位置的迭代器res作為提示,使其成為O(1),還是執行常規的O(log(n))插入?

在快速閱讀標准之后,對void insert(InputIterator first, InputIterator last);的復雜性沒有要求void insert(InputIterator first, InputIterator last); 因此,允許延遲實現具有O(n log(n))復雜度,即使由於以下內容而map1為空,它也可能是線性的。

因為如果輸入范圍是排序的,標准確實需要構造函數的線性復雜性,所以這需要是O(n):

Map<key,val> map1=//filled up in some way;
Map<key,val> map2(map1.begin(),map1.end()); // complexity in O(n)

對於問題的第二部分,因為您想要提示元素應該插入的位置,正確的方法是:

template<class InIter, class OutIter, class ResIter>
ResIter foo(InIter first, OutIter last, ResIter res){
   while(first!=last){
      emplace_hint(res, *first);
      ++first;
      ++res;
   }
return res;
}

不幸的是,標准的地方上的復雜性沒有要求任何emplaceemplace_hint

暫無
暫無

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

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