【问题标题】:vector elements in ascending order [closed]升序的向量元素[关闭]
【发布时间】:2014-11-19 22:23:20
【问题描述】:

我想写一个布尔函数来查看向量中的元素是否按升序排列。 到目前为止我的代码:

bool if_sorted(vector<int>& v) {
int i;
for (; i < v.size(); i++) {
    if(v[i] < v[i + 1]){
        break;
    } else {
        return false; 
}
if(v[i] == v.size())
    return true;
}

在 main() 函数中,我只是用 if_sorted() 函数输入向量 an 的元素,我想查看这些值是否按升序排序。

如何在没有 is_sorted 之类的函数的情况下编写这个布尔函数,或者修改我现有的代码?

【问题讨论】:

  • 1.你忘了说一个问题。 2.你忘了初始化i
  • 我不想使用 is_sorted 或其他函数。仅来自 iostream 库。 i 在 for 循环中被初始化。
  • @user3653164 除了 iostream 什么都不使用?因为作业?就个人而言,如果您只是阅读它,请仅存储最后一个值并检查(prev&lt;curval)。存储向量是浪费内存和时间。
  • 您可以通过多种方式编写代码。如果你想让它工作,你可以先仔细查看if (v[i] &lt; v[i+1]),想一想,然后意识到为什么你的代码不能工作。

标签: c++ function sorting vector boolean


【解决方案1】:
bool if_sorted(vector<int>& v) {

  for (int i = 0; i < v.size() - 1; i++) {
     if(v[i] > v[i + 1]){
        return false; 
  }
  return true;
}

【讨论】:

    【解决方案2】:

    怎么样,不使用std::is_sorted

    Live On Coliru

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    
    template <typename Container, 
             typename It = typename Container::const_iterator, 
             typename T = typename std::iterator_traits<It>::value_type>
    bool if_sorted(Container const &container) {
        using std::begin;
        using std::end;
    
        It l(end(container));
        return l == std::adjacent_find(begin(container),l,std::greater_equal<T>());
    }
    
    int main()
    {
        std::vector<int> v(10);
        do    std::generate_n(v.begin(), v.size(), rand);
        while (!if_sorted(v));
    
        std::cout << "Yay, found a vector that was accidentally sorted: \n";
        std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
    }
    

    打印随机、排序的 10 个整数序列,例如

    Yay, found a vector that was accidentally sorted: 
    338521972 564591732 631716774 818567430 923731840 1036769782 1094628595 1228665979 1863863464 2024865477
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多