C++ void reverse function

2.8k Views Asked by At

We are converting base 10 to a number in a different base(B). I am having trouble with the void reverse function it will not reverse the order of the numbers.

 string convertToBaseB(int num, int b){
int digit;
stringstream answer;
string x="";
    while(num>0){
    digit=num%b;
    num/=b;
    answer<<digit;
}
    return answer.str();}

void reverse(int x[],int size){//reversing the 

for(int k=0; k<size/2; k++){
    int temp=x[k];
    x[k]=x[size-k-1];
    x[size-k-1]=temp;}
}
2

There are 2 best solutions below

4
On

Works for me:

#include <iostream>

using namespace std;

void reverse(int x[],int size)
{

  for(int k=0; k<size/2; k++)
  {
    int temp=x[k];
    x[k]=x[size-k-1];
    x[size-k-1]=temp;
  }
}

int main()
{
  const int sz = 9;
  int* digits;

  digits = new int[sz];

  for (int i=0; i < sz; ++i)
  {
    digits[i] = i;
  }

  reverse(digits, sz);

  for (int i=0; i < sz; ++i)
  {
    cout<<digits[i]<<" ";
  }
  cout<<endl;
}
1
On

Your reverse function works fine. However it doesn't looks like C++ to me... In C++ I would have a vector and do:

std::vector<int> arr;
//... fill arr
std::swap_ranges(&arr[0], &arr[arr.size()/2], arr.rbegin());

If you want to stick with your for loop, at least use std::swap like this

void reverse(int x[],int size) { 
    for(int k=0; k<size/2; k++)
        std::swap(x[k], x[size-k-1]);
}