TheBros OfTheGames TheBros OfTheGames - 19 days ago 5
C++ Question

Error about a void function with a vector argument

I'm having a coding problem about a "simple" exercise about sorting what's inside a vector of n integers number. The problem is that the compiler doesnt accept void as a type for the function sort (And it must be a void function). But I do't really understand why. For the variables the type matches (pointer <-> v.begin() for example) but for the fucntion it does not. Any help appreciated! Here's my code:

#include <iostream>
#include <vector>

typedef std::vector<int>::iterator Vit;


void sort( Vit begin, Vit end){
int len = end - begin;
for(begin; begin < end; ++begin){
for( int i = 1; i < len; ++i){
if(*begin < *(begin +i ) ){
*begin = *(begin + i);
}
}
}
std::cout<< "* ";
for( begin; begin < end; ++begin){
std::cout<< *begin<< " ";
}
std::cout<< "*";
return;
}



int main(){
int n;
std::cin >> n;
std::vector<int> v(n);
for(Vit it = v.begin();it != v.end(); ++it){
std::cin >> *it;
}

void sort (v.begin() , v.end());

}

Answer

There are a few errors. You are incrementing begin in the first for loop, but never resetting it. So the second for loop will never be entered. Each ++begin changes the position of your iterator! The loop for( int i = 1; i < len; ++i) will go to the current position of begin plus i and thus leave the memory. The following should do what you want:

#include <iostream>
#include <vector>

typedef std::vector<int>::iterator Vit;

void sort( Vit begin, Vit end){
  for(Vit pos1=begin; pos1 < end; ++pos1) {
    for(Vit pos2=pos1+1; pos2 < end; ++pos2) {
      if(*pos1 < *pos2 ) {
    int swap = *pos1;
    *pos1 = *pos2;
    *pos2 = swap;
      }
    }
  }
  std::cout<< "* ";
  for(Vit it=begin; it < end; ++it){
    std::cout<< *it<< " ";
  }
  std::cout<< "*";
  return;
}

int main(){
  int n;
  std::cin >> n;
  std::vector<int> v(n);
  for(Vit it = v.begin(); it < v.end(); ++it){
    std::cin >> *it;
  }

  sort (v.begin() , v.end());
}