如何在阅读输入时缩短代码

  • 本文关键字:代码 c++
  • 更新时间 :
  • 英文 :

int testcases;
cin >> testcases;

有没有办法将以上内容缩短为一行?或者更普遍地说,有人能为我提供一个好的资源吗?我可以在这里阅读不一定会影响可读性的代码短缺?

这里没有太多需要缩短的地方;但是,如果您要编写上面的许多实例,您可以编写这样的辅助函数:

int readInt()
{
int i;
cin >> i;
return i;
}

那么你的许多实例可能每个只有一行:

int testcases = readInt();

基于Jeremy的想法,您可以创建一个函数模板,同时创建和读取多个变量:

#include <iostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
template<class... Types, size_t... I>
void readthem(std::istream& is, std::tuple<Types...>& rv, std::index_sequence<I...>) {
// A C++17 fold expression
(is >> ... >> std::get<I>(rv));
}
template<class... Types, class Indices = std::make_index_sequence<sizeof...(Types)>>
auto readvars(std::istream& is) {
std::tuple<Types...> rv;      // A tuple consisting of the types you want
readthem(is, rv, Indices{});
if(not is) throw std::runtime_error("Input failed");
return rv;
}
int main() {
// read an int, a double and a std::string
auto[i, d, s] = readvars<int, double, std::string>(std::cin);
std::cout
<< i << 'n'
<< d << 'n'
<< s << 'n';
}

最新更新