考虑一个cpp函数solve()
。数字的字符串a
(示例测试字符串)作为参数传递给函数solve()
。我希望stdin
读取字符串a
中的数字。
这实际上是个压力测试。因此,在这个应力测试中,这个函数solve()
被提供给return
的一个字符串,这个结果将根据另一个函数solveFast()
得到的另一个结果进行测试。
注意:-函数
solve()
中的算法已经给出了。我希望用我自己的算法(在solveFast()
中)来测试这个算法.保证函数solve()
中的算法对其测试输入提供正确的输出。
#include <bits/stdc++.h>
using namespace std;
int solve(string s) {
// below given: an algorithm that
//uses stdin to take input sample test case (i.e.,not string s)
int n; //number of integers in string s
//ignore the purpose of the code below.
//Just observe that it is taking the inputs as cin (not from string s.
cin >> n;
int first, second, large;
for (int i = 0; i < n - 1; i++) {
if (i == 0) {
cin >> first >> second;
large = (second > first) ? second : first;
if (second < first) first = second;
} else {
cin >> second; // new num
if (second > large) {
first = large;
large = second;
}
else if(second > first){
first = second;
}
}
}
int result = large * first;
return result;
}
int solveFast(string s) {
/*
* my solution here
*/
return result;
}
int32_t main() {
//stress-testing code starts here
while (true) {
string a;
/*
* generating a sample test case and storing it in a string 'a'
*/
int res1 = solve(a);
int res2 = solveFast(a);
if(res1!=res2){
cout << "Wrong answer: " << res1 << " " << res2 << endl;
break;
}
else{
cout << "OK\n";
}
}
//stress-testig code ends
/*
for (int i = 1; i <= t; ++i) {
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
auto result = solve(numbers);
cout << result << endl;
}
*/
return 0;
}
发布于 2020-11-10 17:03:29
将一个std::istream
传递给您的函数,然后从一个字符串构造一个istream。作为一般规则,不要在代码中使用全局变量(如std::cin
),这意味着要进行单元测试。
#include <sstream>
#include <iostream>
int solve(std::istream& input, std::string s) {
std::string variable;
input >> variable;
return 0;
}
void unit_test_solve() {
std::istringstream input("some string");
solve(input, "bla");
}
int real_code() {
solve(std::cin, "bla");
}
https://stackoverflow.com/questions/64772951
复制相似问题