gpt4 book ai didi

c++ - 如何对两个数组进行排序,同时保持它们连接到同一元素?

转载 作者:行者123 更新时间:2023-12-01 19:29:53 24 4
gpt4 key购买 nike

我的程序按姓氏字母顺序排序,并将名字放在旁边,但我希望它也按名字排序。我该怎么办?

    // Before sort
for (int i = 0; i < NUM_PEOPLE; i++) {
cout << first_names[i] << "\t" << last_names[i] << endl;
}

string temp;

for (int pass = 0; pass < NUM_PEOPLE - 1; pass++)
for (int i = 0; i < NUM_PEOPLE - 1; i++)
if (last_names[i] > last_names[i + 1]) {
temp = last_names[i];
last_names[i] = last_names[i + 1];
last_names[i + 1] = temp;
temp = first_names[i];
first_names[i] = first_names[i + 1];
first_names[i + 1] = temp;
}

cout << "After sort:" << endl;

for (int i = 0; i < NUM_PEOPLE; i++)
cout << last_names[i] << "\t" << first_names[i]<< endl;

最佳答案

如果您别无选择,只能将数据放在单独的数组或容器中,则执行这些类型的排序的更好方法是使用额外的索引号数组,并对索引号进行排序。

您希望以这种方式执行操作的原因是,如果您有 2 个以上的数组,则为每个需要交换的数组编写 3 行交换代码会变得更加困难。无论您可能需要保持同步的数组数量是多少,仅交换一个数组会容易得多。

这是一个例子:

//...

// Create an array of indices, starting from 0.
int index[NUM_PEOPLE];
for (int i = 0; i < NUM_PEOPLE; ++i)
index[i] = i;

int temp;

for (int pass = 0; pass < NUM_PEOPLE - 1; pass++)
{
for (int i = 0; i < NUM_PEOPLE - 1; i++)
{
if (last_names[index[i]] > last_names[index[i + 1]])
{
temp = index[i];
index[i] = index[i + 1];
index[i + 1] = temp;
}
}
}
cout << "After sort:" << endl;

for (int i = 0; i < NUM_PEOPLE; i++)
cout << last_names[index[i]] << "\t" << first_names[index[i]]<< endl;

请注意,只有一个项目被交换,那就是索引数组——first_namelast_name数组没有任何改变。请注意,当以排序方式访问数组时(注意最后的输出),我们使用索引数组作为每个单独数组的索引。

这是一个complete example .

<小时/>

这是一个使用 std::sort 的解决方案,它使用与上面解释的相同的技术:

#include <iostream>
#include <string>
#include <algorithm>

const int NUM_PEOPLE = 5;

int main()
{
std::string first_names[NUM_PEOPLE] = { "Joe", "Peter", "Andy", "Anny", "Drake" };
std::string last_names[NUM_PEOPLE] = { "Johnson", "Parker", "Sanchez", "Nguyen", "Bell" };

// Before sort
std::cout << "\nBefore sort:\n" << std::endl;
for (int i = 0; i < NUM_PEOPLE; i++) {
std::cout << first_names[i] << "\t" << last_names[i] << std::endl;
}
int index[NUM_PEOPLE];
for (int i = 0; i < NUM_PEOPLE; ++i)
index[i] = i;

std::sort(index, index + NUM_PEOPLE, [&](int n1, int n2)
{ return last_names[index[n1]] < last_names[index[n2]]; });

std::cout << "\nAfter sort:\n" << std::endl;

for (int i = 0; i < NUM_PEOPLE; i++)
std::cout << last_names[index[i]] << "\t" << first_names[index[i]] << std::endl;
}

输出:

Before sort:

Joe Johnson
Peter Parker
Andy Sanchez
Anny Nguyen
Drake Bell

After sort:

Bell Drake
Johnson Joe
Parker Peter
Nguyen Anny
Sanchez Andy

关于c++ - 如何对两个数组进行排序,同时保持它们连接到同一元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61926849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com