本文介绍了重新排列数组以匹配位置数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个整数数组和一个具有这些整数位置的数组。如何重新排列数字以匹配将数据放入新订单中
ie:
阵列1,2,4
位置阵列1,2,0
数据第三个位置应该移到第一个位置(4)
第一个位置的数据应该移到第二个位置(1)
第二个位置的数据应该移动到第三个地方(2)
我尝试过:
Given an array of integers and an array that has the location of those integers. How do I re-arrange the numbers to match put the data in the new order
i.e:
an array 1,2,4
location array 1,2,0
data in the third spot should be moved to the first spot (4)
data in the first spot should be moved to the second (1)
data in the second spot should be moved to the third spot (2)
What I have tried:
#include <iostream>
using namespace std;
// assign the array to have a maximum of 3 integer values
const int MAX = 3;
int main ()
{
// the elements in the array (the three elements allowed)
int var[MAX] = {10, 100, 200};
// declares ptr as an array of MAX integer pointers
// each element in ptr, now holds a pointer to an int value
int *ptr[MAX];
// for loop increments until it hits the amount of elements in the array
// in this case it will loop three times starting at the 0 index and ending at 2 index (3 elements)
// three integers which will be stored in an array of pointers
for (int i = 0; i < MAX; i++)
{
// assign the address of integer.
ptr[i] = &var[i];
}
// prints out the elements location, i, as well as its value *ptr
for (int i = 0; i < MAX; i++)
{
cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}
return 0;
}
推荐答案
#include <iostream>
using namespace std;
// assign the array to have a maximum of 3 integer values
const int MAX = 3;
int main ()
{
// the elements in the array (the three elements allowed)
int var[MAX] = {10, 100, 200};
// position array
int pos[MAX] = {1, 2, 0};
// destination array
int dest[MAX];
for (int i = 0; i < MAX; i++)
{
dest[pos[i]] = var[i];
}
// prints out the elements location, i, as well as its value *ptr
for (int i = 0; i < MAX; i++)
{
cout << "Value of dest[" << i << "] = ";
cout << dest[i] << endl;
}
return 0;
}</iostream>
这篇关于重新排列数组以匹配位置数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!