我一直在编写一个示例程序来比较一些算法的运行时间,这个程序给我带来了一些麻烦。出于某种原因,整个程序的各个部分都随机跳过了 cin / cout,我不完全确定为什么。这是代码,有问题的行已注释。find_element 已被注释掉以进行调试,但也不起作用。任何建议都会很棒!
#include <iostream>
#include <vector>
using namespace std;
void sort_vect( vector< int >& );
// int find_element( vector< int > );
void print_vect( vector< int > );
int main()
{
vector< int > int_vect;
int input;
int result;
char garbage;
cout << "Enter a number into the vector (Q to quit) > ";
while(cin >> input && input != 'Q' && input != 'q')
{
int_vect.push_back(input);
cout << "> ";
}
// The following doesn't help
// cin >> garbage;
// cout << "Garbage : " << garbage << endl;
if (int_vect.size() == 0)
{
cout << "Vector empty" << endl;
return 1;
}
sort_vect(int_vect);
print_vect(int_vect);
cout << "What value do you want > ";
cin >> input;
cout << "Result : " << int_vect[input-1] << endl;
return 0;
} // main()
void sort_vect( vector< int >& int_vect)
{
vector< int >::iterator vect_iterator;
vector< int >::iterator temp_iterator;
int temp_store = NULL;
for(vect_iterator = int_vect.begin(); vect_iterator != int_vect.end(); vect_iterator++)
{
for (temp_iterator = vect_iterator; temp_iterator != int_vect.begin(); temp_iterator--)
{
while(*temp_iterator < *(temp_iterator-1))
{
temp_store = *temp_iterator;
*temp_iterator = *(temp_iterator-1);
*(temp_iterator-1) = temp_store;
}
}
}
cout << "Vector sorted." << endl << endl;
}
// int find_element( vector< int > int_vect)
// {
// int input;
// char garbage;
//
// cout << "Enter value to be returned (5 = 5th smallest) > ";
// cin >> input;
// cout << "Value for input : " << input << endl;
//
// return int_vect[input-1];
// }
void print_vect( vector< int > int_vect )
{
vector< int >::iterator vect_iterator = int_vect.begin();
while(vect_iterator != int_vect.end())
{
cout << *vect_iterator << endl;
vect_iterator++;
}
} // print_vect()
根据请求,输出(注意:输入错误,因为我忘记正确使用输入作为索引,但目前这不是问题):
Enter a number into the vector (Q to quit) > 1
> 2
> 4
> 6
> 5
> 3
> 4
> q
Vector sorted.
1
2
3
4
4
5
6
What value do you want > Result : 4