sort用法(升降排序)

sort用法

头文件#include<algorithm>
sort(start,end,cmp)
参数

  • start表示要排序数组的起始地址;
  • end表示数组结束地址的下一位;//[start,end)
  • cmp用于规定排序的方法,可不填,默认升序。

1. 由小到大升序排序

#include<iostream>
#include<algorithm>
using namespace std;
//从小到大升序排序
int main()
{
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
        cout<<a[i]<<"  ";
        cout<<endl;
        sort(a,a+10);//指针
    for(int i=0;i<10;i++)
        cout<<a[i]<<"  ";
        cout<<endl;
    return 0;
}

2.由大到小降序排序

#include<iostream>
#include<algorithm>
using namespace std;
//从大到小降序排序
**//加入比较函数compare**
bool compare(int a,int b)
{
    return a>b;
}

int main()
{
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
        cout<<a[i]<<"  ";
        cout<<endl;
        sort(a,a+10,compare);//在这里就不需要对compare函数传入参数了
    for(int i=0;i<10;i++)
        cout<<a[i]<<"  ";
        cout<<endl;
    return 0;
}

实例

L2-002 链表去重
L2-003 月饼(贪心算法)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给你一些指导。 1. 商品价格升降排序: 如果你使用的是 Vue.js,你可以使用它提供的 `v-for` 指令来循环渲染商品列表,并且在 `v-for` 指令中使用 `v-bind` 指令来绑定商品价格。例如: ``` <div v-for="product in products"> <p>{{ product.name }}</p> <p>价格:{{ product.price }}</p> </div> ``` 如果你想要实现价格排序,你可以在 Vue.js 中使用 `Array.prototype.sort()` 函数来对商品列表进行排序。例如: ``` this.products.sort(function(a, b) { return a.price - b.price; }); ``` 这会将商品列表按价格从低到高排序。如果你想要按价格从高到低排序,你可以将 `a.price - b.price` 改为 `b.price - a.price`。 2. 商品删除: 如果你想要实现商品删除,你可以使用 Vue.js 提供的 `v-on` 指令来绑定一个事件监听器。例如: ``` <div v-for="product in products"> <p>{{ product.name }}</p> <p>价格:{{ product.price }}</p> <button v-on:click="removeProduct(product)">删除</button> </div> ``` 这会在每个商品下面渲染一个“删除”按钮,并且在按钮上绑定了一个 `removeProduct` 方法。 在 Vue.js 实例中,你可以定义这个 `removeProduct` 方法来从商品列表中删除商品。例如: ``` methods: { removeProduct: function(product) { var index = this.products.indexOf(product); this.products.splice(index, 1); } } ``` 这个方法会接收一个商品对象作为参数,并且会使用 `Array.prototype.indexOf()` 函数来找到这个商品在商品列表中的索引,然后使用 `Array.prototype.splice()` 函数来从商品列表中删除这个商品。 希望以上内容对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值