如何根据数组对应向量的值对数组进行排序
How can I sort an array according to values of its corresponding vector?
我想根据相应向量的值对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;
}
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为