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

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

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

之后的 2 个元素

Example:

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?

以下将提供您想要的输出或至少放弃(可能效率不高)来解决您的问题。希望,评论可以指导您完成。

See Output

#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;
}