Advertisement
AntonioVillanueva

sort vector c++

Jun 20th, 2025
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. /* Antonio Villanueva
  2. C++ class uses the bubble method
  3. to sort a vector without using sort
  4. sorts numbers or letters*/
  5.  
  6. #include <iostream>
  7. #include <vector>
  8. using namespace std;
  9.  
  10. template <typename T>
  11. class Ordena {
  12.    
  13.     public:
  14.     Ordena (vector <T> &v) : v(v){};
  15.     void ordenaElementos(){//sort vector public
  16.         ordenaE();
  17.     }
  18.    
  19.     void printVector (){//print vector
  20.         for (const T &elem:v){
  21.             cout <<elem<<" ";
  22.         }
  23.         cout <<endl;
  24.     }
  25.  
  26.     private:
  27.     vector<T>& v;
  28.    
  29.     void swapElems (int x,int y){//swap elems
  30.         T tmp;
  31.         tmp=v[x];
  32.         v[x]=v[y];
  33.         v[y]=tmp;
  34.     }
  35.    
  36.     void ordenaE(){ //sort a vector
  37.         for (size_t x=0 ;x < v.size();x++){
  38.             for (size_t y=0 ;y < v.size();y++){
  39.                 if ( v[x] < v[y] ){
  40.                     swapElems(x,y);                
  41.                 }
  42.             }
  43.         }
  44.     }
  45.    
  46.    
  47. };
  48.  
  49. int main(void)
  50. {
  51.     //Test of a numeric vector
  52.     //vector <int> v {3,5,1,8,7};
  53.     //Ordena <int> o(v);
  54.    
  55.     //Test of a  char vector   
  56.     vector <char> v {'x','a','y','b','w'}; 
  57.     Ordena <char> o(v);
  58.    
  59.     o.ordenaElementos();
  60.     o.printVector();
  61.    
  62.     //test the local version of the vector
  63.     for (const auto &elem:v){
  64.         cout<<elem<<" ";
  65.     }
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement