빈도 맵 포팅하기
Coddy의 Rust 개발자를 위한 C 코스 레슨. 48개 중 47번째.
챌린지
중급C 배열과 모듈식 함수를 사용해 이 Rust 빈도 맵을 옮기세요. 입력은 -100부터 100까지의 정수 최대 64개입니다. format_counts(values,n,out,capacity)는 서로 다른 값을 오름차순으로 value=count 형식으로 쉼표로 구분해 기록합니다. 값이 없으면 empty를 사용하세요. 입력을 변경하지 마세요. capacity는 최소 1024입니다.
잠금이 해제된 소스 파일과 헤더 파일을 수정하세요. 공개 API 선언은 표시된 잠금 상태의 main.c에서 직접 호출하는 방식과 호환되도록 유지하세요. main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한, 모든 숫자 작업 데이터는 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 드라이버가 표시된 경우 입력 분석과 출력을 담당합니다.
Rust 참조
use std::io::{self,Read};use std::collections::BTreeMap;
fn main(){let mut text=String::new();io::stdin().read_to_string(&mut text).unwrap();let mut counts=BTreeMap::<i32,i32>::new();for word in text.split_whitespace(){*counts.entry(word.parse().unwrap()).or_default()+=1;}let out:Vec<String>=counts.iter().map(|(n,c)|format!("{}={}",n,c)).collect();println!("{}",if out.is_empty(){String::from("empty")}else{out.join(",")});}
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;int before[64];memcpy(before,values,n*sizeof *values);char out[1024];format_counts(values,n,out,sizeof out);if(memcmp(before,values,n*sizeof *values)!=0)return 3;puts(out);return 0;}
Rust 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러