我写了一个代码,试图在向量中找到重复。在重复的情况下,它将将该位置添加到列表中。例如,一个序列100 110 90 100 140 90 100
将是一个二维向量。第一个维度包含唯一的字母(或数字),并附加重复列表作为第二个维度。所以结果看起来像
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),代码非常慢,退出压缩功能可能需要一天时间。有没有机会通过使用std::list
而不是加速std::vec
?因为list
is 对于顺序的事情表现更好。但是我只想知道它是否有帮助。如果它有用,那么我已经更改了一些其他代码。
寻找任何建议。