Sorting 2D Vector in C++ | Set 1 (By row and column)

本文介绍了如何在C++中对二维向量进行排序。第一种情况是按行对二维向量的特定行进行升序排序,利用`sort()`函数和一维向量的迭代器。第二种情况是根据特定列对整个二维向量进行排序,通过提供自定义函数作为`sort()`的第三个参数来实现。文章还包括贡献者提供的其他相关排序文章推荐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What is a 2D Vector?
A 2D vector is vector of vectors. It is an matrix implemented with the help of vectors. 二维的vector,是vector中的元素是vector,用vector实现的矩阵。

// C++ code to demonstrate 2D vector 
#include<iostream> 
#include<vector> // for 2D vector 
using namespace std; 

int main() 
{ 
	// Initializing 2D vector "vect" with 
	// values 
	vector< vector<int> > vect{
  {1, 2, 3}, 
							{4, 5, 6}, 
							{7, 8, 9}}; 

	// Displaying the 2D vector 
	for (int i=0; i<vect.size(); i++) 
	{ 
		for (int j=0; j<vect[i].size() ;j++) 
			cout << vect[i][j] << " "; 
		cout << endl; 
	} 

	return 0; 
} 

Output:

1 2 3
4 5 6
7 8 9

Case 1 : To sort a particular row of 2D vector. 对二维的vector的特定行进行排序。
This type of sorting arranges a selected row of 2D vector in ascending order . This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. 这种排序对二维vector中的特定的行进行升序排序。用函数sort()实现,传一维vector的迭代器作为参数。

// C++ code to demonstrate sorting of a 
// row of 2D vector 
#include<iostream> 
#include<vector> // for 2D vector 
#include<algorithm> // for sort() 
using namespace std; 

int main() 
{ 
	// Initializing 2D vector "vect" with 
	// values 
	vector< vector<int> > vect{
  {3, 5, 1}, 
							{4, 8, 6}, 
							{7, 2, 9}}; 
	// Number of rows; 
	int m = vect.size(); 

	// Number of columns (Assuming all rows 
	// are of same size). We can have differ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值