【问题标题】:Is it possible to add the elements in the array during iteration?是否可以在迭代期间添加数组中的元素?
【发布时间】:2019-05-22 08:24:19
【问题描述】:

我想对元素进行排序。

例如:最初,我得到5 元素并对其进行排序。 问题是下一个 5 元素应该添加到前面的 5 元素中,然后它应该执行排序。

是否有任何内置函数可以在向量中执行?

【问题讨论】:

  • 您可以使用std::sort(v.begin(), v.end()); 对向量进行排序。只需在获得其他元素后调用它。但话又说回来,我可能会误解你的问题,所以如果你发布你的代码、你的预期结果和你当前的结果会很有帮助。
  • 你能用伪代码做一个例子吗?

标签: c++ algorithm function sorting stdvector


【解决方案1】:

是否有任何内置函数可以在 c++ 中使用向量来执行此操作?

std::vector 是一个序列容器,它不执行任何自动排序,除非您使用std::sort 对其进行排序。

如果元素是唯一的,您可能正在寻找 std::set,如果元素是唯一的,您可能正在寻找 std::multiset 不是唯一的这种行为。 compare 函数按照标准要求进行排序。

【讨论】:

    【解决方案2】:

    如果您将元素插入到 当前排序 向量中的所有大于它们的元素之后的第一个位置,则该向量保持排序状态。

    您可以通过std::lower_bound找到该职位

    std::vector<int> currently_sorted{ 1, 2, 5, 6, 7 };
    for (auto i : { 3, 4, 10, 9, 8 })
    {
         auto it = std::lower_bound(currently_sorted.begin(), currently_sorted.end(), i);
         currently_sorted.insert(it, i);
    }
    
    assert(std::is_sorted(currently_sorted.begin(), currently_sorted.end()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-26
      • 2011-08-30
      • 2018-06-29
      • 1970-01-01
      • 2016-11-30
      • 2020-11-13
      • 2013-07-09
      相关资源
      最近更新 更多