C++ C++;反转数组中元素的程序
我编写了以下代码来尝试反转给定数组中的元素:C++ C++;反转数组中元素的程序,c++,arrays,algorithm,C++,Arrays,Algorithm,我编写了以下代码来尝试反转给定数组中的元素: #include <iostream> using namespace std; int main(int argc, char **argv) { int numbers[6] = {1, 5, 9, 10, 12, 18}; int b = 0; int a = 5; for (int i = 0; i < 3; ++i) { b = numbers[i];
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int numbers[6] = {1, 5, 9, 10, 12, 18};
int b = 0;
int a = 5;
for (int i = 0; i < 3; ++i)
{
b = numbers[i];
numbers[i] = numbers[a-i];
numbers[a-i] = b;
}
for(int c = 0; c < 6; ++c)
cout << *(numbers) << endl;
return 0;
}
#包括
使用名称空间std;
int main(int argc,字符**argv)
{
整数[6]={1,5,9,10,12,18};
int b=0;
INTA=5;
对于(int i=0;i<3;++i)
{
b=数字[i];
数字[i]=数字[a-i];
数字[a-i]=b;
}
对于(int c=0;c<6;++c)
cout这是第二个for循环,您忘记添加c
for(int c = 0; c < 6; ++c)
cout << *(numbers + c) << endl;
for(int c=0;c<6;++c)
cout这是第二个for循环,您忘记添加c
for(int c = 0; c < 6; ++c)
cout << *(numbers + c) << endl;
for(int c=0;c<6;++c)
coutchangecoutchangecout您可以尝试以下方法:
for(int i = 0; i < ARRAY_SIZE; ++i) {
//a^=b^=a^=b; //SWAP a with b
numbers[i] ^= numbers[ARRAY_SIZE-i] ^= numbers[i] ^= numbers[ARRAY_SIZE-i];
}
for(int i=0;i
它将反转数组中的所有元素。:)您可以尝试以下操作:
for(int i = 0; i < ARRAY_SIZE; ++i) {
//a^=b^=a^=b; //SWAP a with b
numbers[i] ^= numbers[ARRAY_SIZE-i] ^= numbers[i] ^= numbers[ARRAY_SIZE-i];
}
for(int i=0;i
它将反转数组中的所有元素。:)要求人们发现代码中的错误不是特别有效。您应该使用调试器(或添加打印语句)若要隔离问题,然后构造一个。最好使用std::vector和std::reverse。而不是只使用一行代码。另请参见。或者,如果使用C++11,请尝试使用std::array
让人们发现代码中的错误,这样效果不是特别好。您应该使用调试器(或添加打印语句)要隔离问题,然后构造一个。最好使用std::vector和std::reverse。而不是只使用一行代码。另请参见..或者如果使用C++11,请尝试std::array
谢谢,我没有意识到它这么简单!谢谢,我没有意识到它这么简单!