在std::list和std::vector之间进行选择
Choosing between std::list and std::vector
我写了一个代码,试图在一个向量中找到重复。在重复的情况下,它会将该位置添加到列表中。例如,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
对于顺序的事情表现得更好。但是,我只是想知道,这是否有帮助。如果它是有用的,那么我已经改变了一些其他的代码。
征求意见
- 你为什么不尝试一下,自己测量一下结果呢?
- 不,
list
对"顺序的事情"没有更好的表现。所有的表现都明显更差。
它唯一真正的优点是list
中的元素是稳定的,并且指向元素的指针/迭代器不会随着列表的修改或增长而消除。
相关文章:
- 可组合的lambda/std::函数与std::可选
- std::可选实现为联合与字符[]/aligned_storage
- 为什么移动 std::可选不重置状态
- std::可选::value_or()-惰性参数求值
- 用于比较基元类型的std::可选的有趣程序集
- std::可选参数会创建副本吗?
- 在 C++11 上下文中使用 std::可选
- 使用什么 std::可选 or std::unique_ptr
- 为什么null std ::可选的被认为小于任何值,而不是更多
- std::可选的默认构造函数不是 gcc 中的 constexpr?
- 为什么const rvalue合格的std ::可选:: value()返回const rvalue参考
- 如何在C++中使用 std::可选?
- 使用 std::可选标准化,我们可以停止在新代码中使用 nullptr 并弃用它吗?
- clang 5:std ::可选的实例螺钉std :: is_constructiblibstiblesiblinsib
- 使用STD ::可选避免函数中的默认参数有任何优势
- 如何初始化用户定义的数据类型的STD ::可选
- STD ::可选的微不足道默认构造函数
- std::可选和提升::可选是否尊重托管对象的对齐限制?
- 为什么当T不可移动时,STD ::可选的移动构建体不会被删除
- constexpr std ::可选的可能实现