ner*_*tor 0 c++ sorting vector
我有一个函数原型:
void bubbleSort(std::vector<float>);
Run Code Online (Sandbox Code Playgroud)
和实施:
void bubbleSort(std::vector<float> inputVector)
{
std::cout << "Executing bubble sort." << std::endl;
int pass;
int comparisons;
float hold;
for (pass = 1; pass < VECSIZE; pass++)
{
for (comparisons = 0; comparisons < VECSIZE - 1; comparisons++)
{
if (inputVector[comparisons] > inputVector[VECSIZE + 1])
{
hold = inputVector[comparisons];
inputVector[comparisons] = inputVector[comparisons + 1];
inputVector[comparisons + 1] = hold;
}
}
}
for (int i = 0; i < VECSIZE; i+=10)
{
std::cout << "Element " << i << " is " << inputVector[i] << std::endl;
}
return;
}
Run Code Online (Sandbox Code Playgroud)
它是从这个调用的main:
#define VECSIZE 1000
int main(void)
{
std::string fileName = "randFloats.txt";
std::cout << "Processing " << fileName << "..." << std::endl;
std::ifstream fileInput(fileName);
//vector to hold the floats
std::vector<float> fltVector(VECSIZE);
if(fileInput.is_open())
{
std::string line;
int i = 0;
while(getline(fileInput, line))
{
fltVector[i] = (::atof(line.c_str()));
i++;
}
}
bubbleSort(fltVector);
}
Run Code Online (Sandbox Code Playgroud)
基本上,main函数采用1000个元素长的浮点文件,将其读入向量结构,并将其发送到要排序的函数.由于我已经完成了某种语言指针的工作,所以已经太久了,所以当我传递std::vector<float>给bubbleSort函数时,我发现它没有输出一个有序向量.我如何将向量传递给函数以使其排序?
这里需要冒泡排序......我只是为了自己的目的这样做,以便通过内存管理来恢复自我.
这是一个用于测试的输入文件: 1000行文件
有几个问题.他们之中有一些是:
向量按值传递,而不是通过引用传递,因此您正在修改本地副本.
您正在访问越界数据:inputVector[VECSIZE + 1]不存在.
使用inputVector.size()而不是使用VECSIZE宏.理想的情况下,使用begin(),end()和迭代器.
根本不需要VECSIZE.只需在阅读循环中附加向量:
while(getline(fileInput, line))
fltVector.push_back(::atof(line.c_str()));
Run Code Online (Sandbox Code Playgroud)"自从我用语言中的指针完成任何工作已经太久了"它是C++,你可以做很多而不用直接触摸指针:)
| 归档时间: |
|
| 查看次数: |
935 次 |
| 最近记录: |