[英]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
对于顺序的事情表现更好。 但是,我只想知道它是否可以提供帮助。 如果有用,那么我需要更改一些其他代码。
寻找任何建议。
list
对于“顺序事物”的执行效果不佳。 它对所有事情的表现都非常差。 它唯一的真正优点是list
中的元素是稳定的,并且在列表被修改或增长时,不会消除指向元素的指针/迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.