Menu
CoddyTech

最终挑战:游程编码记录

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

challenge icon

挑战

简单

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

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

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

extends Node

func _ready() -> void:
    var text := ""
    var chunk := OS.read_string_from_stdin()
    while not chunk.is_empty():
        text += chunk + " "
        chunk = OS.read_string_from_stdin()
    var values: Array[int] = []
    for token in text.replace("\t", " ").replace("\r", " ").replace("\n", " ").split(" ", false):
        values.append(int(token))
    var groups := PackedStringArray()
    var i := 0
    while i < values.size():
        var j := i + 1
        while j < values.size() and values[j] == values[i]:
            j += 1
        groups.append("%d:%d" % [values[i], j - i])
        i = j
    print(" ".join(groups) if not groups.is_empty() else "empty")

亲手试试

#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";
}

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

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