Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

c++ - Having trouble creating an array that shows how the indices were moved in another 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;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Here is an example:

#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]] << "
";

    // show the indices
    std::cout << "

Here are the indices:
";
    for (size_t i = 0; i < tumor.size(); ++i)
       std::cout << indices[i] << "
";
}

int main()
{ test(); }

Live Example

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...