簡體   English   中英

在std :: list和std :: vector之間選擇

[英]Choosing between std::list and std::vector

我寫了一個代碼,試圖找到向量中的重復。 如果重復,它將把位置添加到列表中。 例如, 100 110 90 100 140 90 100的序列將是2D向量。 第一維包含唯一字母(或數字),重復列表作為第二維附加。 所以結果看起來像

100 -> [0 3 6]
110 -> [1]
90 -> [2 5]
140 -> [4]

代碼很簡單

typedef unsigned long long int ulong;
typedef std::vector<ulong> aVector;
struct entry {
  entry( ulong a, ulong t ) {
    addr = a;
    time.push_back(t);
  }
  ulong addr;
  aVector time;
};

// vec contains original data
// theVec is the output vector
void compress( aVector &vec, std::vector< entry > &theVec )
{
   aVector::iterator it = vec.begin();
   aVector::iterator it_end = vec.end();
   std::vector< entry >::iterator ait;
   for (ulong i = 0; it != it_end; ++it, ++i) {  // iterate over input vector
     ulong addr = *it;
     if (theVec.empty()) {  // insert the first item
       theVec.push_back( entry(addr, i) );
       continue;
     }
     ait = find_if( theVec.begin(), theVec.end(), equal_addr(addr));
     if (ait == theVec.end()) { // entry doesn't exist in compressed vector, so insert
       theVec.push_back( entry(addr, i) );
     } else { // write down the position of the repeated number (second dimension)
       ait->time.push_back(i);
     }
   }
}

find_if將看起來像這樣

struct equal_addr : std::unary_function<entry,bool>
{
  equal_addr(const ulong &anAddr) : theAddr(anAddr) {}
  bool operator()(const entry &arg) const { return arg.addr == theAddr; }
  const ulong &theAddr;
};

問題是,對於中等大小的輸入(在我的測試中為20M),代碼非常慢,並且可能需要一天的時間才能退出compress函數。 通過使用std::list而不是std::vec可以加速嗎? 因為list對於順序的事情表現更好。 但是,我只想知道它是否可以提供幫助。 如果有用,那么我需要更改一些其他代碼。

尋找任何建議。

  1. 您為什么不嘗試一下,自己衡量結果呢?
  2. 不, list對於“順序事物”的執行效果不佳。 它對所有事情的表現都非常差。

它唯一的真正優點是list中的元素是穩定的,並且在列表被修改或增長時,不會消除指向元素的指針/迭代器。

暫無
暫無

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

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