简体   繁体   English

C ++ void反向函数

[英]C++ void reverse function

We are converting base 10 to a number in a different base(B). 我们正在将基数10转换为其他基数(B)中的数字。 I am having trouble with the void reverse function it will not reverse the order of the numbers. 我在使用void reverse函数时遇到麻烦,它不会颠倒数字的顺序。

 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;}
}

Your reverse function works fine. 您的反向功能可以正常工作。 However it doesn't looks like C++ to me... In C++ I would have a vector and do: 但是在我看来,它看起来并不像C ++。在C ++中,我将拥有一个向量并执行以下操作:

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 如果您想坚持使用for循环,请至少使用std :: swap这样的

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM