[英]How to swap across center in array?
編寫一個 C++ 函數 swapAcrossCenter(),它將指針數組和數組大小作為參數,並在中心交換其值。 數組的大小應該是奇數。 示例:假設值為 2 5 6 7 8 函數調用前(輸入):2 5 6 7 8 函數調用后(輸出):8 7 6 5 2 但需要用戶給定的通用函數和數組大小。 這是大小固定的硬代碼。我想制作一個代碼,其中用戶將給出奇數大小。然后程序找到中心並交換數組。
int size =5;
int array[size] ={1,2,3,4,5};
if(size==5)
{
int a,b;
a =array[0];
b=array[1];
array[0]=array[4];
array[1]=array[3];
array[3]=b;
array[4]=a;
}
for(int i=0;i<5;i++)
{
cout<<array[i];
}
進化:從 C 到 C++。 . .
首先,您需要注意您的函數反轉數組。
然后。 你永遠不應該在 C++ 中使用 C 風格的普通數組。 改用std::array
或std::vector
。 這些類知道底層數組的大小。
最后一個是最好的解決方案。 向量有多少個元素並不重要。 反向始終有效。
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
// Solution 1: Pure C-Code, full manual implementation
void swapAcrossCenter1(int arr[], int size) {
int first{ 0 };
int last{ size };
while ((first != last) && first != --last) {
int temp = arr[first];
arr[first++] = arr[last];
arr[last] = temp;
}
}
// Solution 2: Pure C-Code, use swap subfunction
void swapManual(int* v1, int* v2) {
int temp = *v1;
*v1 = *v2;
*v2 = temp;
}
void swapAcrossCenter2(int arr[], int size) {
int first{ 0 };
int last{ size };
while ((first != last) && first != --last) {
swapManual(&arr[first++], &arr[last]);
}
}
// Solution 3: A little bit of C++ Code, use std::algorithm for swap
void swapAcrossCenter3(int arr[], int size) {
int first{ 0 };
int last{ size };
while ((first != last) && first != --last) {
std::iter_swap(&arr[first++], &arr[last]);
}
}
// Solution 4: A little bit more of C++ Code, use std::algorithm for reverse
void swapAcrossCenter4(int arr[], int size) {
std::reverse(&arr[0], &arr[size]);
}
int main() {
int test[5] = { 2,4,6,8,10 };
// Solution 1: Pure C-Code, full manual implementation
swapAcrossCenter1(test, 5);
std::copy(&test[0], &test[5], std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
// Solution 2: Pure C-Code, use swap subfunction
swapAcrossCenter2(test, 5);
std::copy(&test[0], &test[5], std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
// Solution 3: A little bit of C++ Code, use std::algorithm for swap
swapAcrossCenter3(test, 5);
std::copy(&test[0], &test[5], std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
// Solution 4: A little bit more of C++ Code, use std::algorithm for reverse
swapAcrossCenter4(test, 5);
std::copy(&test[0], &test[5], std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
// Solution 5: C++ Code, use std::algorithm for reverse, but with plain C-Style array
std::reverse(&test[0], &test[5]);
std::copy(&test[0], &test[5], std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
// Solution 6: C++ Code, use std::algorithm for reverse, with std::vector
std::vector<int> v{ 1,3,5,7,9 };
std::reverse(v.begin(), v.end());
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); std::cout << "\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.