main.cpp
cpp
#include <iostream>
#include <vector>
#include <ctime>
#include "Swap.h"
using namespace std;
int main()
{
Array myArrays;
srand(time(0));
for (int i = 0; i < 7; ++i) {
int tempArray = (rand() % 100); // 生成0到99之间的随机数
myArrays.addArrayMember(tempArray);
}
myArrays.outPutOriginalResult();
myArrays.swapArray();
myArrays.outPutNowResult();
return 0;
}
Swap.cpp
cpp
#include "Swap.h"
using namespace std;
void Array::swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void Array::addArrayMember(int member)
{
Arrays.push_back(member);
}
// 实现通过指针倒置数组内容的函数,原地修改
void Array::reverseArrayInPlace(int* arr, int size)
{
for (int i = 0; i < size / 2; ++i) {
swap(arr[i], arr[size - 1 - i]);
}
}
void Array::swapArray()
{
int* arrayPtr = Arrays.data();
reverseArrayInPlace(arrayPtr, Arrays.size());
}
void Array::outPutOriginalResult()
{
cout << "随机产生的数组内容为:";
for (int num : Arrays) {
cout << num << ",";
}
cout << endl;
}
void Array::outPutNowResult()
{
cout << "倒置的数组内容为(原地修改):";
for (int num : Arrays) {
cout << num << ",";
}
cout << endl;
}
Swap.h
cpp
#include <iostream>
#include <vector>
using namespace std;
class Array
{
public:
void swap(int& a, int& b); // swap
void addArrayMember(int member);
void reverseArrayInPlace(int* arr, int size);
void outPutOriginalResult();
void swapArray();
void outPutNowResult();
private:
vector<int> Arrays;
};