我应该使用哪种类型?

时间:2018-08-01 09:42:24

标签: c++ sorting vector

我用C ++编写程序,给了一个包含10个元素的矢量(总是),每个元素都有一个称为position的值,它是一个int值。 我希望此向量始终被排序,因此,一旦我对其进行更新,就立即使用std :: sort对其进行排序。 大部分时间都是这样,例如向量有99%的时间已经被完全排序。

我还是应该使用std :: sort吗?还是有更好的方法?

ps:更新是:从点云中获取一个点,针对某个外部因素计算它属于矢量的哪个元素,并增加指定的矢量元素的计数。根据此计数器,我将向向量添加一个新元素,并删除一个旧元素。

2 个答案:

答案 0 :(得分:1)

首先,如果您始终有10个元素,我将使用std::array。这将启用一些重要的优化,因为在编译时就知道大小。

如果您知道容器已排序,则可以使用此信息使用std::lower_boundstd::upper_bound查找元素的新位置,然后根据需要移动相邻的元素以为其放置位置。 / p>

// replaces the element found at position replace_idx with new_value
// precondition: arr is sorted. 0 <= replace_idx < 10
// postcondition: arr is sorted
auto replace(std::array<E, 10>& arr, std::size_t replace_idx, const E& new_value)
{
    auto remove_it = arr.begin() + replace_idx;
    auto insert_it = std::lower_bound(arr.begin(), arr.end(), new_value);

    if (insert_it < remove_it)
        std::move(insert_it, remove_it, insert_it + 1);
    else if (insert_it > remove_it)
        std::move(remove_it + 1, insert_it + 1, remove_it);

    *insert_it = new_value;
}

别忘了个人资料个人资料个人资料

免责声明:未经测试

答案 1 :(得分:0)

通常,插入排序对于“几乎排序的数组”非常有效,特别是当它们很小时。

据我所知,C ++ std :: sort使用了一组排序技术,包括快速排序和插入排序,它们会随着算法的进行在它们之间进行切换。 这意味着std :: sort在大多数情况下实际上都会为您提供任何尺寸的最佳性能。

另一个好的解决方案是始终保持阵列排序,并从头开始扫描直到到达合适的位置,然后将其插入正确的插槽中。这可以线性工作,也可以使用vector的insert()函数。

相关问题