如何使用STL中的sort与vector对二维数组(矩阵)实现按行排序?

xybxbh 2015-03-26 01:45:24
例如数组如下:
18 64 36 2
7 15 28 94
16 61 33 5
希望排序后的结果是
2 18 36 64
7 15 28 94
5 16 33 61
作为一个初学者,要用vector!要用sort!要用vector!要用sort!要用vector!要用sort!重要的事情说三遍。谢谢大大们了!
...全文
555 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sduxiaoxiang 2015-03-26
  • 打赏
  • 举报
回复
对二维数组的每一行直接调用sort就是
xybxbh 2015-03-26
  • 打赏
  • 举报
回复
谢谢楼上的答案们,但是输进去有语法错误……虽然我看着觉得没有()贴一下我原来的 #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int m, n; cout << "输入m、n"; cin >> m >> n; vector<vector<int>> a(m, vector<int>(n)); int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) a[i][j] = 1 + rand() % 100; for (i = 0; i < m; i++){ for (j = 0; j < n; j++) cout << a[i][j] << "\t"; cout << endl; } cout << "\n"; for (i = 0; i < m; i++) sort(a.begin(), a.end()); for (i = 0; i < m; i++){ for (j = 0; j < n; j++) cout << a[i][j] << "\t"; cout << endl; } return 0; } 这样能运行但是不是我想要的结果,求改正,再次感谢
michael2988 2015-03-26
  • 打赏
  • 举报
回复

    int myints[3][4] =
    {
        {18, 64, 36, 2},
        {7, 15, 28, 94},
        {16, 61, 33, 5}
    };

    for (int i = 0; i < 3; i++)
    {
        std::vector<int> myvector(myints[i], myints[i] + 4);
        std::sort(myvector.begin(), myvector.end());
        std::vector<int>::iterator it;
        for (it = myvector.begin(); it != myvector.end(); it++)
        {
            std::cout << *it << std::endl;
        }
    }
jiht594 2015-03-26
  • 打赏
  • 举报
回复

vector<int> a, b;
	a.push_back(18);//18 64 36 2
	a.push_back(64);
	a.push_back(36);
	a.push_back(2);

	b.push_back(7);
	b.push_back(15);
	b.push_back(28);
	b.push_back(94);

	vector<vector<int> > vec2;
	vec2.push_back(a);
	vec2.push_back(b);

	for (vector<vector<int> >::iterator it = vec2.begin(); it != vec2.end(); ++it)
	{
		sort(it->begin(), it->end());
	}

	for (vector<vector<int> >::iterator it = vec2.begin(); it != vec2.end(); ++it)
	{
		for (vector<int>::iterator itor = it->begin(); itor != it->end(); ++itor)
		{
			cout << *itor << " ";
		}
		cout << endl;
	}

64,684

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧