Menu
CoddyTech

最终:游程记录

Coddy 面向 Java 开发者的 C++ 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

输入:以空白分隔的整数。将连续相同的值压缩为以空格连接的“值:计数”组;如果没有整数,则输出 empty。这是对下方完整源代码参考实现的最终移植。

在 exercise.hpp 和 exercise.cpp 中实现声明的 API。两个文件都可以编辑;请保留公共签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它也会在指定的地方独立检查公共 API 的行为。在 API 中返回值,不要在其中打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。

将这个完整的 Java 参考程序移植到所需的 C++ API。这两个程序使用相同的整数输入测试数据。

import java.util.*;
public class Example {

public static void main(String[] args) {
Scanner in=new Scanner(System.in);List<String> groups=new ArrayList<>();Integer previous=null;int count=0;while(in.hasNextInt()){int n=in.nextInt();if(previous!=null && n!=previous){groups.add(previous+":"+count);count=0;}previous=n;count++;}if(previous!=null)groups.add(previous+":"+count);System.out.println(groups.isEmpty()?"empty":String.join(" ",groups));
}
}

亲手试试

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);std::cout<<runs(v)<<"\n";
}

面向 Java 开发者的 C++中的所有课

自己练习: C++ 在线编译器