[英]Sorting a 2d matrix by their sum using vector<vector<int>> c++?
I m new to vector matrix.我是向量矩阵的新手。
C++ and using vector> please! C++ 和使用矢量>拜托!
cin >> n >> m;
vector<vector<int>> A(n, vector<int> (m));
for (auto& rows : A)
for (auto& x : rows)
cin >> x;
sort(A.begin(), A.end());
My sort isn t good though.不过我的类型不太好。 Thanks!谢谢!
Either use the standard algorithm std::accumulate
declared in the header <numeric>
and a lambda expression that uses the algorithm and will be passed to the standard algorithm std::sort
or write similar functions yourself.使用在 header <numeric>
中声明的标准算法std::accumulate
和使用该算法并将传递给标准算法std::sort
的 lambda 表达式,或者自己编写类似的函数。
Here are two demonstrative programs that implement the both approaches.以下是实现这两种方法的两个演示程序。
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <ctime>
int main()
{
size_t n = 0, m = 0;
std::cin >> n >> m;
std::vector<std::vector<int>> v( n, std::vector<int>( m ) );
std::srand( ( unsigned int )std::time( nullptr ) );
for ( auto &row : v )
{
for ( auto &item : row )
{
item = std::rand() % ( n * m );
}
}
for ( const auto &row : v )
{
for ( const auto &item : row )
{
std::cout << std::setw( 2 ) << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
auto less = []( const auto &row1, const auto &row2 )
{
return std::accumulate( std::begin( row1 ), std::end( row1 ), 0ll ) <
std::accumulate( std::begin( row2 ), std::end( row2 ), 0ll );
};
std::sort( std::begin( v ), std::end( v ), less );
for ( const auto &row : v )
{
for ( const auto &item : row )
{
std::cout << std::setw( 2 ) << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
And和
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstdlib>
#include <ctime>
long long int accumulate( const std::vector<int> &v, long long int init = 0 )
{
for ( const auto &item : v ) init += item;
return init;
}
bool less( const std::vector<int> &v1, const std::vector<int> &v2 )
{
return accumulate( v1 ) < accumulate( v2 );
}
int main()
{
size_t n = 0, m = 0;
std::cin >> n >> m;
std::vector<std::vector<int>> v( n, std::vector<int>( m ) );
std::srand( ( unsigned int )std::time( nullptr ) );
for ( auto &row : v )
{
for ( auto &item : row )
{
item = std::rand() % ( n * m );
}
}
for ( const auto &row : v )
{
for ( const auto &item : row )
{
std::cout << std::setw( 2 ) << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
std::sort( std::begin( v ), std::end( v ), less );
for ( const auto &row : v )
{
for ( const auto &item : row )
{
std::cout << std::setw( 2 ) << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
If to enter sizes of vectors equal to 3
and 4
then the output might look like如果输入向量的大小等于3
和4
,那么 output 可能看起来像
3 3 1 4
6 1 5 7
5 6 7 2
3 3 1 4
6 1 5 7
5 6 7 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.