我写了一个代码,试图在向量中找到重复.如果重复,它会将位置添加到列表中.例如,序列100 110 90 100 140 90 100将是2D矢量.第一维包含唯一的字母(或数字),并且重复列表作为第二维附加.所以结果看起来像
100 -> [0 3 6]
110 -> [1]
90 -> [2 5]
140 -> [4]
Run Code Online (Sandbox Code Playgroud)
代码非常简单
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
问题是,对于中等输入大小(我的测试为20M),代码非常慢,可能需要一天时间才能退出压缩功能.有没有机会加速使用std::list而不是std::vec?因为list顺序事物的表现更好.但是我只是想知道,如果它可以帮助与否.如果它有用,那么我已经改变了一些其他代码.
寻找任何建议.
list对于"顺序事物"表现不佳.它对一切都表现得更糟.唯一真正的优点是a list中的元素是稳定的,而元素的指针/迭代器在修改或增长列表时不会被消除.