我试图对我随机想到的整数 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/