안정적이고 결정적인 출력
Coddy의 C++ 개발자를 위한 Go 코스 레슨. 48개 중 17번째.
C++의 std::sort와 Go의 sort.Slice는 선택한 시퀀스를 변경합니다. 두 정렬 콜백 모두 엄격한 미만 관계를 나타내지만, 호출 가능한 객체의 시그니처는 서로 다릅니다. 특히 Go 슬라이스는 기반 배열을 공유할 수 있으므로, 원래 순서가 API 계약의 일부라면 정렬하기 전에 저장 공간을 복사하세요.
sort.Ints는 슬라이스를 수정합니다. 호출자가 원본을 유지해야 한다면 먼저 복사하세요. 맵을 결정적인 순서로 출력하려면 키를 모아 정렬한 다음, 그 순서대로 값에 접근하세요. 문자열의 사전식 순서는 바이트 순서이며, 로캘에 따른 정렬 순서가 아닙니다.
C++ 예제
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
std::vector<std::string> words{"pear", "fig", "plum"};
words.erase(std::remove_if(words.begin(), words.end(), [](const auto& w) { return w.size() < 4; }), words.end());
std::stable_sort(words.begin(), words.end(), [](const auto& a, const auto& b) { return a.size() < b.size(); });
for (const auto& w : words) std::cout << w << '\n';
}소스 출력:
pear
plumGo 예제
package main
import ("fmt";"sort")
func main(){xs:=[]int{4,1,3}
sort.Sort(sort.Reverse(sort.IntSlice(xs)))
fmt.Println(xs)}Go 출력:
[4 3 1]챌린지
쉬움숫자를 오름차순으로 정렬하여 별도의 저장 공간에 반환하세요. 원본 슬라이스의 입력 순서는 유지하세요.
선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필수 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력은 JSON 형식이 아닌 Go의 대괄호 형식을 사용합니다.
코드는 exercise.go에 작성하세요. main.go에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 하나의 평평한 package main을 유지하고, 두 번째 main을 추가하지 마세요.
직접 해보기
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=Ints(0); before0:=fmt.Sprint(a0)
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러