Sorting out vector elements

This is a discussion on Sorting out vector elements within the C++ Programming forums, part of the General Programming Boards category; Is there any function that selects directly the smallest and the greatest number in a vector or do I have ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    50

    Sorting out vector elements

    Is there any function that selects directly the smallest and the greatest number in a vector or do I have to write an algorithm for that?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Use the min_element and max_element functions.

    Code:
    #include <vector>
    #include <iostream>
    #include <algorithm>
    
    int main()
    {
        std::vector<int> intVect;
    
        intVect.push_back(18);
        intVect.push_back(21);
        intVect.push_back(36);
        intVect.push_back(14);
        intVect.push_back(9);
    
        std::cout << "Min value is: " << *std::min_element(intVect.begin(),intVect.end()) << std::endl;
        std::cout << "Max value is: " << *std::max_element(intVect.begin(),intVect.end()) << std::endl;
    
    }
    Output:
    Code:
    Min value is: 9
    Max value is: 36
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Or sort the vector and just walk through - better approach if you need the second-smallest etc.

    std::sort
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting algorithms, worst-case input
    By Leftos in forum C++ Programming
    Replies: 17
    Last Post: 06-15-2009, 01:33 PM
  2. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  3. sorting structure members using pointers
    By robstr12 in forum C Programming
    Replies: 5
    Last Post: 07-25-2005, 05:50 PM
  4. Still Needing Help : selection sorting
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 10-14-2001, 08:41 PM
  5. selection sorting
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 10-13-2001, 08:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21