いくつかのアルゴリズムの実行時間を比較するサンプル プログラムを書いていますが、これが原因で問題が発生しています。何らかの理由で、プログラム全体のさまざまな部分で 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