如何根据数组对应向量的值对数组进行排序

How can I sort an array according to values of its corresponding vector?

本文关键字:数组 排序 何根 向量      更新时间:2023-10-16

我想根据相应向量的值对row数组进行排序。这意味着,我有一个向量,它包含相同长度的整数的向量。CCD_ 2。根据vect的值,我想对我的数组row进行排序。row包含N元素,其中第一个元素给出了我们应该为行考虑的数字。如果row[0]==2,那么我们应该只关心row[0]之后的2个元素。

示例:

Input:   vect = {{0,2,3},{2,1,5},{1,2,4}} 
row  = {3,0,1,2,-1,-2,15}

注意,在row中,我们只关心第2到第4个元素,因为它的第一个元素是3(表示vect的大小,即row[0] = vect.size()(。

我想根据值023, 215 and 124对数组和向量进行排序。也就是说,在对向量进行排序后,根据其元素的新位置,我应该通过考虑其第一个元素来对数组进行排序。(只需对所需的进行排序。(

所以我想得到的是:

Output: vect = {{0,2,3},{1,2,4},{2,1,5}}
row  = {3,0,2,1,-1,-2,15}

非常感谢您的帮助。以下是代码:

std::vector<int> seq;
int pair;
while(pair!=-1) {
seq.push_back(letter[pair--]);
}
.
.
.
int* row = new int[N]; // N is the input
std::vector<std::vector<int>> vect;
vect.resize(row[0]);
for(int e=0;e<row[0];e++){
for(int elm=0;elm<seq.size();elm++)
vect[e].push_back(outputs[seq[elm]][row[e+1]]);
}
sort(vect,row); // sort both?

以下内容将提供您想要的输出,或者至少提供(可能无效(来解决您的问题。希望,评论可以引导你通过。

请参阅输出

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::vector<int>>  vect = {{0,2,3},{2,1,5},{1,2,4}};
std::vector<int> row = {3,0,1,2,-1,-2,15};
// new vector:  pair of integer -> representing the rows of vect and index
std::vector<std::pair<std::string, int>> newVect;
newVect.reserve(vect.size());
int index = 0;
for(const std::vector<int>& each_row: vect)
{
std::string str;             // each row of vect to a single integer string
for(const int Integer: each_row) str += std::to_string(Integer);
newVect.emplace_back(std::make_pair(str, index));
++index;
}
// sort the new vector, according to the whole 2D vector row(which is a single string)
std::sort(newVect.begin(), newVect.end(), [](const auto& lhs, const auto& rhs)
{
return lhs.first < rhs.first;
});
// now you can actually store the sorted vect
vect.clear();
for(auto index = 1; index <= row[0]; ++index)
{
row[index] = newVect[index-1].second;  // replace the row indexes which are sorted
std::vector<int> vect_row;
// change each chars of string back to corresponding row elements
for(const char Integer: newVect[index-1].first)
vect_row.emplace_back(static_cast<int>(Integer - '0'));
// store to original vector
vect.emplace_back(vect_row);
}
// to print
for(const std::vector<int>& each_row: vect)
{
for(const int Intger: each_row)
std::cout << Intger << " ";
std::cout << std::endl;
}
for(const int it: row) std::cout << it << " ";
return 0;
}