Vector-Sort

Sort by

recency

|

300 Discussions

|

  • + 0 comments
    int n;
        cin >> n;
    
        vector<int> numbers(n);
        for (int i = 0; i < n; i++) {
            cin >> numbers[i];
        }
    
        sort(numbers.begin(), numbers.end());
    
        for (int i = 0; i < n; i++) {
            cout << numbers[i] << " ";
        }
        cout << endl;   
    
  • + 0 comments

    Instead of using a for loop paired with push_back() (which can result in allocations that could otherwise be avoided), use the explicit constructor, std::vector<T>(int) (requiring direct initialisation via a parenthesised list) which constructs a std::vector of a given size:

    int main()
    {
        int size {};
        std::cin >> size;
        
        // Constructs a 'std::vector' of given size
        std::vector<int> v (size);
        
        // Loops through the vector by reference
        // setting its elements to inputted values
        for(auto& i : v)
            std::cin >> i;
            
        std::sort(v.begin(), v.end());
        
        for(auto i : v)
            std::cout << i << ' ';
        
        return 0;
    }
    
  • + 0 comments

    int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    vectorv;

     int n;
     cin>>n;
     for(int i=0;i<n;i++) {
         int ele;
         cin>>ele;
         v.push_back(ele);
     }
    
     sort(v.begin(),v.end());
    
     for(int a : v) {
         cout<<a<<" ";
     }
    
    return 0;
    

    }

  • + 0 comments

    include

    include

    include

    include

    include

    using namespace std;

    int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */

    vector<int> v;
    int size{};
    int num{};
    
    cin >> size;
    
    while(cin >> num)
    {
        v.push_back(num);
    }
    
    sort(v.begin(), v.end());
    
    for(auto i : v)
    {
        cout << i << " ";
    }
    
    return 0;
    

    }

  • + 0 comments
    int main() {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
        int size;
        cin>>size;
        vector<int> v;
        int ele;
        for(int i=0; i<size; i++)
        {
            cin>>ele;
            v.push_back(ele); 
        }
        sort(v.begin(), v.end());
        for(auto i=v.begin(); i!=v.end(); i++)
        {
            cout<<*i<<" "; 
        }
        return 0;
    }