最终:游程记录
Coddy 面向 Go 开发者的 C++ 课程的第 47 课,共 48 课。
挑战
简单输入:以空格分隔的整数。将连续相同的值压缩为“值:计数”组,并用空格连接;如果没有整数,则输出 empty。本挑战最后会移植下面展示的完整源代码参考实现。
在 exercise.hpp 和 exercise.cpp 中实现声明的 API。这两个文件都可以编辑;请保留公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。另在有说明的地方,它也会独立检查公开 API 的行为。在 API 中返回值,而不是打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
将这个完整的 Go 参考程序移植到所需的 C++ API。两个程序使用相同的整数输入测试数据。
package main
import("bufio";"fmt";"os";"strings")
func main(){
in:=bufio.NewReader(os.Stdin)
groups:=[]string{}
previous,count:=0,0
for {var n int;if _,err:=fmt.Fscan(in,&n);err!=nil{break};if count>0 && n!=previous{groups=append(groups,fmt.Sprintf("%d:%d",previous,count));count=0};previous=n;count++}
if count>0{groups=append(groups,fmt.Sprintf("%d:%d",previous,count))}
if len(groups)==0{fmt.Println("empty")}else{fmt.Println(strings.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";
}
面向 Go 开发者的 C++中的所有课
自己练习: C++ 在线编译器