安定した決定的な出力
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
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を維持し、2つ目の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オンラインコンパイラ