题解 | #使用算法#

使用算法

https://www.nowcoder.com/practice/ba99206d258c4f96a69866bdf77162b4

1.这道题主要是使用STL的库函数,我们要在头部添加algorithm库。

2.掌握sort()函数,sort函数是从小到大排序的。

3.使用for循环反向遍历就行了。

4.掌握vector的本质,首先他是一个容器,其次他的首指针指向的是第一个元素的下标,最后太还有一个尾后指针。指向的是最后一个元素的下标的后一位。因此在反向遍历时,vector所存储的实际数组大小是size()-1。

#include <iostream>
#include <vector>
// write your code here......
#include<algorithm>

using namespace std;

int main() {

    int num;
    vector<int> v;
    for (int i = 0; i < 5; i++) {
        cin >> num;
        v.push_back(num);
    }

    // write your code here......
    sort(v.begin(), v.end());
    auto size = v.size(); // vector的尾后元素(所以实际长度应为size-1)
    for (int i = size - 1; i >= 0; i--) {
        cout << v[i] << " ";
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务