Menu
CoddyTech

稳定且确定的输出

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

C++ 的 std::sort 和 Go 的 sort.Slice 会修改选定的序列。两者的排序回调都表示严格小于关系,但可调用对象的签名不同。如果原始顺序属于 API 契约的一部分,请在排序前复制数据,尤其是因为 Go 切片可能与其底层数组共享存储。

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
plum

Go 示例

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]
challenge icon

挑战

简单

按升序返回数字,并使用独立存储空间。保留原切片中的输入顺序。

实现已声明的 API;返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合的标准输出采用 Go 的方括号格式,而不是 JSON。

你的代码写在 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)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

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

自己练习: Go 在线编译器