创建数组以显示索引如何在另一个数组中移动时遇到麻烦 [英] Having trouble creating an array that shows how the indices were moved in another array

查看:78
本文介绍了创建数组以显示索引如何在另一个数组中移动时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要制作的功能的要点.但是,每当我打印出order_of_change数组时,关于肿瘤值移动到的位置,其值总是完全不正确.我将if语句中的i更改为肿瘤[i],以确保肿瘤[i]确实与temp_array中的相应值匹配,并且确实匹配.谁能告诉我怎么了?

This is the gist of the function I'm trying to make. However whenever I print out the order_of_change array its values are always completely off as to where the values of tumor were moved to. I changed the i inside of the if statement to tumor[i] to make sure that tumor[i] was indeed matching its corresponding value in temp_array and it does. Can anyone tell me whats going wrong?

double temp_array[20];
for (int i = 0; i < 20; i++)
{
    temp_array[i] = tumor[i];
}

//sort tumor in ascending order
sort(tumor, tumor + 20); //tumor is an array of 20 random numbers

int x = 0; //counter
int order_of_change[20]; //array to house the index change done by sort
while (x < 20) //find where each value was moved to and record it in order_of_change
{
    for (int i = 0; i < 20; i++)
    {
        if (temp_array[x] == tumor[i])
        {
            order_of_change[x] = i;
            x += 1;
        }
    }
}

推荐答案

要对数据进行排序,但只有索引显示排序顺序,您需要做的就是创建一个以升序排列的索引数组(从0开始),然后将其用作std::sort标准的一部分.

To sort the data, but only have the indices show the sort order, all you need to do is create an array of indices in ascending order (starting from 0), and then use that as part of the std::sort criteria.

这里是一个例子:

#include <algorithm>
#include <iostream>
#include <array>

void test()
{
    std::array<double, 8> tumor = {{4, 3, 7, 128,18, 45, 1, 90}};
    std::array<int, 8> indices = {0,1,2,3,4,5,6,7};

    //sort tumor in ascending order
    std::sort(indices.begin(), indices.end(), [&](int n1, int n2)
    { return tumor[n1] < tumor[n2]; });

    // output the tumor array using the indices that were sorted      
    for (size_t i = 0; i < tumor.size(); ++i)
       std::cout << tumor[indices[i]] << "\n";

    // show the indices
    std::cout << "\n\nHere are the indices:\n";
    for (size_t i = 0; i < tumor.size(); ++i)
       std::cout << indices[i] << "\n";
}

int main()
{ test(); }

在线示例

即使示例使用std::array,原理也相同.根据数据中的项目对索引数组进行排序. tumor数组保持不变,而无需移动实际元素.

Even though the example uses std::array, the principle is the same. Sort the index array based on the items in the data. The tumor array stays intact without the actual elements being moved.

如果数组(或std::vector)中的项目在移动时复制起来很昂贵,但仍希望能够在不实际对项目进行排序的情况下生成已排序的列表,则也可以使用此技术.

This technique can also be used if the items in the array (or std::vector) are expensive to copy if they're moved around, but still want to have the ability to produce a sorted list without actually sorting items.

这篇关于创建数组以显示索引如何在另一个数组中移动时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆