重新排列数组以匹配位置数组

编程入门 行业动态 更新时间:2024-10-07 10:25:29
本文介绍了重新排列数组以匹配位置数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个整数数组和一个具有这些整数位置的数组。如何重新排列数字以匹配将数据放入新订单中 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; }

推荐答案

试试这个: Try this: #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>

更多推荐

重新排列数组以匹配位置数组

本文发布于:2023-11-29 15:08:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   排列   位置

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!