• C++ vector generated via rand() and print with fixed width


    #include <iostream>
    #include <uuid/uuid.h>
    #include <sstream>
    #include <ctime>
    #include <unistd.h>
    #include <ostream>
    #include <fstream>
    #include <istream>
    #include <random>
    #include <vector>
    
    using namespace std;
    
    static char *dtValue = (char *)malloc(20);
    static char *uuidValue = (char *)malloc(40);
    char *getUuid3()
    {
        uuid_t newUUID;
        uuid_generate(newUUID);
        uuid_unparse(newUUID, uuidValue);
        return uuidValue;
    } 
    
    char *getTimeNow()
    {
        time_t rawTime = time(NULL);
        struct tm tmInfo = *localtime(&rawTime);
        strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo);
        return dtValue;
    }
    
    
    void vector8();
    
    int main()
    {
        vector8();
        return 0;
    }
    
    void vector8()
    {
        srand(time(NULL));
        int len = 100;
        vector<int> vec;
        for (int i = 0; i < len; i++)
        {
            vec.push_back(rand());
        }
    
        cout << "Original order:" << endl;
        vector<int>::iterator itr = vec.begin();
        int colWidth = 0;
        while (itr != vec.end())
        {
            if (++colWidth >= 8)
            {
                colWidth = 0;
                cout << endl;
            }
            printf("%-10d\t", *itr++); 
        }
    
        for (int i = 0; i < len; i++)
        {
            for (int j = i + 1; j < len; j++)
            {
                if (vec[i] > vec[j])
                {
                    int temp = vec[i];
                    vec[i] = vec[j];
                    vec[j] = temp;
                }
            }
        }
    
        cout << "\n\nSort ascendingly:" << endl;
        vector<int>::iterator itr2 = vec.begin();
        colWidth = 0;
        while (itr2 != vec.end())
        {
            if (++colWidth >= 8)
            {
                colWidth = 0;
                cout << endl;
            }
            printf("%-10d\t", *itr2++); 
        }
        cout << "\n\nNow finished in vector8() and now is " << getTimeNow() << endl;
        free(uuidValue);
        free(dtValue);
    }

    Compile

    g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid

    #include <iostream>#include <uuid/uuid.h>#include <sstream>#include <ctime>#include <unistd.h>#include <ostream>#include <fstream>#include <istream>#include <random>#include <vector>

  • 相关阅读:
    Delete Node in a Linked List leetcode
    Remove Linked List Elements leetcode
    Remove Linked List Elements
    Remove Element leetcode
    Merge Sorted Array leetcode
    Min Stack leetcode
    Valid Palindrome leetcode
    [LeetCode] 1. Two Sum
    [LeetCode] 520. Detect Capital
    [LeetCode] 791. Custom Sort String
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15739917.html
Copyright © 2020-2023  润新知