c++ - 在 C++ 中排序然后打印 vector

标签 c++ sorting vector iostream

我试图对我随机想到的整数 vector 进行排序,并在排序后打印它。但是,当它打印时,它与原始未排序的 vector 相同。发生这种情况是因为我的 bricksort 算法不正确还是因为我打印 vector 的方法错误?任何建议将不胜感激。

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int brickCount = 0;

void bricksort(vector <int> a)
{
    bool sorted = false;
    while( sorted != true )
    {
        sorted = true;
        for( int i = 1; i < a.size( ) - 1; i += 2 )
        {
            if( a[i] > a[i + 1] ) 
            {
                swap( a[i], a[i + 1] );
                brickCount++;
                sorted = false;
            }
        }
        for( int i = 0; i < a.size() - 1; i += 2 )
        {
            if( a[i] > a[i + 1] )
            {
                swap( a[i], a[i + 1] );
                brickCount++;
                sorted = false;
            }
        }
    }
}

int main()
{
    vector<int>::iterator pos;
    vector <int> nums = {9,8,5,6,76,3,84,234,1,4,6,4,345,54,23,76,85,83,82,61};
    //vector <int> nnums = bricksort(nums);
    bricksort(nums);
    for (pos=nums.begin(); pos!=nums.end(); ++pos) 
    {
        cout << *pos << ' ';
    }
    cout << endl << "brickCount is: " << brickCount << endl;
}

最佳答案

您正在将 vector 的拷贝传递给 bricksort .尝试将函数签名更改为:void bricksort(vector <int> &a)改为传递引用。

关于c++ - 在 C++ 中排序然后打印 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23238663/

相关文章:

C:字符数组数组按字母顺序排序

c++ - 将 vector<Foo> 转换为 vector<double> 并找到最小值

c++ - vector 错误消息以及如何在 C++ 中将对象插入到 vector 中?

c++ - 为什么 C++ 链接器不提示缺少这些函数的定义?

php - 不显示 php 中 ksort 的最后一个值

c++ - Boost Spirit 如何将本地引用作为属性传递

c# - 如何使用自定义属性属性对类的属性进行排序

c++ - 将 vector 幅度减小特定长度的有效方法?

c++ - Visual C++ 2010 : LNK1104, LNK1181 - .obj 文件不会自动生成

c++ - 如何使用uccp api开发一个lync客户端