gpt4 book ai didi

c++ - 根据另一个对象的值对类中的二维对象进行排序并赋值 C++

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:24 25 4
gpt4 key购买 nike

我要根据类中另一个对象的值对类中的二维 vector 对象进行排序。我的课看起来像这样: 类(Class)问题 { 民众: vector >位; vector >等待时间; vector 处理作业; 问题1; 常量我= 3; 常数 j = 4;我想根据 problem1.processingJob[ j] 但我不知道如何对此应用排序功能。我可以找到一些关于 1D 变量的主题,但找不到关于 2D 对象的任何主题。因此,对于 processingJob 的最低值,假设我们有以下内容:

  processingJob[0]=73  
processingJob[1]=44
processingJob[2]=32
processingJob[3]=52

此处 processingJob[2] 的值最低,因此:
位[0][2]=位[1][2]=位[2][2]=1
第二小的值是 processingJob[1]=44,因此:

 bit[0][1] and bit[1][1] and bit[2][1]=2

第三低的值是 processingJob[4]=52,因此在输出中我有:

bit[0][3] and bit[1][3] and bit[2][3]=3 

最大值是 processingJob[0]=73,因此在输出中我有:

bit[0][0] and bit[1][0] and bit[2][0]=4

其实它只需要基于processingJob排序然后给每个bit[i][j]排序

最佳答案

使用您的类(class)(问题中的格式困惑):

class problem {
public:
std::vector<std::vector<short int>> bit;
std::vector<std::vector<float>> WaitingTime;
std::vector<int> processingJob;
};

我能够使用这段代码解决问题:

// initializing a 3 x 4 problem 
// I'm just writing this down so you know what data I used to test my code
problem problem1{};
problem1.processingJob = { 73, 44, 32, 52 };
problem1.bit = std::vector<std::vector<short int>>(3, std::vector<short int>(4, 0));

// one way to solve this would be to use std::pairs to pair elements in processingJob
// to their respective indices
std::vector<std::pair<int, size_t>> v_pairs; // store the pairs in this vector
for (size_t i = 0; i != problem1.processingJob.size(); ++i) {
v_pairs.push_back({ problem1.processingJob[i], i });
}

// now sort the vector of pairs using std::sort. We sort with respect to the .first members
// of the pair, which (if you recall) were the values copied from processingJob.
// std::sort sorts by .first members by default.
std::sort(v_pairs.begin(), v_pairs.end());

// now we can index the 2D 'bit' vector using indices paired to the processingJob elements
// we iterate through v_pairs to get said indices
for (size_t k = 0; k != v_pairs.size(); ++k) {
for (auto& subvector : problem1.bit) {
// set the corresponding values
subvector[v_pairs[k].second] = k + 1;
}
}

我不能声称代码是类型安全的,因为在

subvector[v_pairs[k].second] = k + 1;

size_t 类型的 k 被转换为 short int 时。但我会把类型安全和所有这些留给你。

此外,我不能声称该代码是最有效的,但它至少是一个可行的起点。我绝对同意@super ,我认为 bit 使用 1D vector 而不是 2D 会更好。将它从 2D 转换为 1D 是微不足道的,所以我也会把它留给你。

如果要插入许多元素,您也可以在开始向 v_pairs 添加元素之前调用 .reserve()

关于c++ - 根据另一个对象的值对类中的二维对象进行排序并赋值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374940/

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