我试着编写一个关于找到两个序列的中位数的程序,这并不难,但我停止了购买输入两个序列部分。
以前从不考虑这个问题,总是尝试while(cin>> temp)
,但不知道为什么这次失败。
当我编译它时,第一个循环输入是OK,但是当第二个循环开始时,编译器会发出" vector iterator而不是dereferencable"
#include <iostream>
#include <vector>
using namespace std;
template< class T>
T median(vector<T>& s1, vector<T>& s2) {
T m(0);
auto itr1 = s1.begin();
auto itr2 = s2.begin();
int counts = (s1.size() + s2.size() -1 ) / 2 ;
for (int i = 0; i < counts; ++i){
if ((*itr1 < * itr2) && ( itr1+1 != s1.end()))
++itr1;
else
++itr2;
}
m = (*itr1 + *itr2) / 2;
return m;
}
int main() {
vector<int> s1;
vector<int> s2;
cout << " Please input the number in the first sequence " << endl;
int temp;
while (cin >> temp) {
s1.push_back(temp);
}
cout << " Please input the number in the second sequence " << endl;
int temp2;
while (cin >> temp2){
s2.push_back(temp2);
}
cout << " The median of these two sequences is " << median<int>(s1, s2) << endl;
return 0;
}
答案 0 :(得分:0)
您可以使用非数字输入作为停止的符号。 它会停在任何键上,不仅是'q',而且你还可以添加额外的支票等等。
cout << " Please input first sequence numbers (press 'q' to finish)" << endl;
while (cin >> temp)
s1.push_back(temp);
cin.clear();
// ignore all symbols before '\n'
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << " Please input second sequence numbers (press 'q' to finish)" << endl;
while (cin >> temp)
s2.push_back(temp);