【问题标题】:Sorting then printing a vector in C++在 C++ 中排序然后打印一个向量
【发布时间】:2014-04-23 08:20:05
【问题描述】:

我正在尝试对我随机得出的整数向量进行排序,并在排序后打印它。但是,当它打印时,它与原始的未排序向量相同。这是因为我的砖排序算法不正确还是因为我打印向量的方法错误?任何建议将不胜感激。

#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;
}

【问题讨论】:

  • 您确定要编写自己的排序吗? std::sort 高效且正确: std::sort(a.begin(), a.end());

标签: c++ sorting vector iostream


【解决方案1】:

您正在将向量的副本传递给bricksort。尝试将函数签名更改为:void bricksort(vector &lt;int&gt; &amp;a) 以改为传递引用。

【讨论】:

  • 做到了。谢谢!
【解决方案2】:

尝试将 vector&lt;int&gt; 的引用传递给函数:

void bricksort(vector<int>&a)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多