关于输入数据
About input data
我试图编写一个有关查找两个序列中间的程序,这并不难,但是我停止购买输入两个序列部分。
以前从未考虑过,总是尝试过while(cin>> temp)
,但不知道为什么这次失败了。
当我对其进行编译时,第一个循环输入就可以了,但是当第二个循环开始时,编译器会发出"矢量迭代器不可用"
#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;
}
您可以使用非数字输入作为符号来停止。它将停止在任何键上,不仅" 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);
相关文章:
- c ++数据输入并读回列表中的结构结构中的数组
- 为什么我不能从结构将数据输入到字符数组中?
- C 如何忽略错误数据输入
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- 使用 for 循环多次将数据输入到 txt 文件
- C 从文本文件中将数据输入INT矢量
- 将数据输入两个字符串
- 带有 QSqlTableModel 的 QTableView 的数据输入
- C++用户将数据输入 2D 数组的最简单方法是什么?
- C++LinkedList数据输入
- 将数据输入到 2-D 数组中,这是如何工作的
- C++ 将数据输入私有向量时遇到问题(使用无效)
- 使数据输入字段记住其值,从一次运行到下一次运行
- C++ 将数据输入到用户定义类型的向量
- 我不知道如何正确地将数据输入到地图中
- 如何通过输入终止数据输入
- WHILE循环和数据输入
- 不按我的要求显示数据输入表单
- 用键盘将数据输入Qt GUI:按下回车键时会产生意想不到的副作用
- c++为不符合条件的数据输入创建循环