反转和切换数组中的值C++

reversing and switching values in an array C++

本文关键字:C++ 数组      更新时间:2023-10-16

有人可以帮我如何以相反的顺序交换数组 A[10] 和数组 B[10] 中的值吗?这是我到目前为止的代码,另外,如果所需的值是一个数字,我的代码将是什么..不是一封信?

#include <iostream>
#include <iomanip>
using namespace std;
using std::setw;
void REVERSE(char *);
int A, B;
int main()
{
    cout << "word in A: " << endl;
    cin >> char A[];
    cout << "word in B: " << endl;
    cin >> char B[];

    REVERSE(A);
    REVERSE(B);
    return 0;
}
void REVERSE (char *A)
{
    int counter = 0;
    while(A[counter] != '')
        counter++;
    for(int i=counter-1;i>=0;i--)
        cout<<A[i];
    cout<<endl;
};

if(A>B)
{
    temp = A;
    A = B;
    B = temp;
}   

你的代码中有几个错误。

您将AB声明为整数值。但是,您(可能)尝试将它们读取为char[](字符数组)。除了这一行cin >> char[] A应该给你一个编译器错误之外,这甚至没有意义。不能将字符值存储在整数中。

如果您尝试读取字符串或字符数组,请将AB声明为一个。

此外,代码末尾的尾随 if 语句也会让你的编译器抱怨。C++不是脚本语言。如果语句不在函数内部,则不会执行语句。

以下程序执行我认为您尝试的方法:

#include <iostream>
#include <algorithm> // include algorithm to use std::reverse
using namespace std;
int main()
{
    string A, B;  // declare A and B to be a string, there is no need to declare them at global scope
    cout << "word in A: ";
    cin >> A;
    cout << "word in B: ";
    cin >> B;
    reverse(A.begin(), A.end()); // reverses A
    reverse(B.begin(), B.end()); // reverses B
    cout << A << " " << B << endl; // prompt A and B
} 

如果要读取整数并将其转换为字符串以反转它们,请尝试以下操作:

#include <iostream>
#include <algorithm> // include algorithm to use std::reverse
using namespace std;
int main()
{
    int A, B;  // declare A and B to be a int
    cout << "word in A: ";
    cin >> A;
    cout << "word in B: ";
    cin >> B;
    string strA(to_string(A)); // convert A into a string
    string strB(to_string(B)); // convert B into a string
    reverse(strA.begin(), strA.end()); // reverses string version of A
    reverse(strB.begin(), strB.end()); // reverses string version of B
    cout << strA << " " << strB << endl; // prompt strA and strB
} 

注意:要使用to_string()您需要使用 c++11 标准

std::string stringA(A);
std::string stringB(B);
std::reverse(stringA.begin(), stringA.end());
std::reverse(stringB.begin(), stringB.end());

标准::反向 - 反向

int *ptr=&a;
int i=0;
while(i < n-1)
{
     ptr++;
     i++;
}
i=0;
while(i <n-1)
{
    b[i]=*ptr;
    ptr--;
    i++;
}

希望这有帮助!.如果我正确理解了您的问题,很高兴为您提供进一步的帮助。