Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to sort a vector in C++, but the compiler says " 'sort' was not declared in this scope "

I’m doing a programming exercise that asks me to write a function that takes an array of integers and sorts it in this way: first puts all even integers sorted in ascending order, after that puts all the odd integers in descending order.

The code I wrote is the following:

#include <iostream>
#include <vector>
using namespace std;

void weirdSort(int v[], int n)
{
      vector<int> evenvec;           //My idea is to allocate two vectors which will collect
      vector<int> oddvec;            //the even integers separated from the odd ones
      int a = 0;                     
      int b = 0;                     //I use a and b to save the number of even and odd integers
      for(int i = 0; i < n; i++)
      {
            if(v[i]%2 == 0)
            {
                  evenvec.push_back(v[i]);
                  ++a;
            }
            else
            {
                  oddvec.push_back(v[i]);
                  ++b;
            }
      }
      sort(evenvec.begin(), evenvec.end());   //the compiler doesn't like this line
      sort(oddvec.begin(), oddvec.end()), greater<int>());
      for(int i = 0; i < a; i++)
            v[i] = evenvec[i];
      for(int i = 0; o < b; i++)
            v[i+a] = oddvec[i];
}         

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Import std::sort with #include <algorithm>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading