Debian Codegraph @

examples/iteratorwithindex/iteratorwithindex.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8 "fmt"
9 "strings"
10
11 "github.com/emirpasic/gods/v2/sets/treeset"
12 )
13
14 // IteratorWithIndexExample to demonstrate basic usage of IteratorWithIndex
15 func main() {
16 set := treeset.New[string]()
17 set.Add("a", "b", "c")
18 it := set.Iterator()
19
20 fmt.Print("\nForward iteration\n")
21 for it.Next() {
22 index, value := it.Index(), it.Value()
23 fmt.Print("[", index, ":", value, "]") // [0:a][1:b][2:c]
24 }
25
26 fmt.Print("\nForward iteration (again)\n")
27 for it.Begin(); it.Next(); {
28 index, value := it.Index(), it.Value()
29 fmt.Print("[", index, ":", value, "]") // [0:a][1:b][2:c]
30 }
31
32 fmt.Print("\nBackward iteration\n")
33 for it.Prev() {
34 index, value := it.Index(), it.Value()
35 fmt.Print("[", index, ":", value, "]") // [2:c][1:b][0:a]
36 }
37
38 fmt.Print("\nBackward iteration (again)\n")
39 for it.End(); it.Prev(); {
40 index, value := it.Index(), it.Value()
41 fmt.Print("[", index, ":", value, "]") // [2:c][1:b][0:a]
42 }
43
44 if it.First() {
45 fmt.Print("\nFirst index: ", it.Index()) // First index: 0
46 fmt.Print("\nFirst value: ", it.Value()) // First value: a
47 }
48
49 if it.Last() {
50 fmt.Print("\nLast index: ", it.Index()) // Last index: 3
51 fmt.Print("\nLast value: ", it.Value()) // Last value: c
52 }
53
54 // Seek element starting with "b"
55 seek := func(index int, value string) bool {
56 return strings.HasSuffix(value, "b")
57 }
58
59 it.Begin()
60 for found := it.NextTo(seek); found; found = it.Next() {
61 fmt.Print("\nNextTo index: ", it.Index())
62 fmt.Print("\nNextTo value: ", it.Value())
63 } /*
64 NextTo index: 1
65 NextTo value: "b"
66 NextTo index: 2
67 NextTo value: "c"
68 */
69
70 it.End()
71 for found := it.PrevTo(seek); found; found = it.Prev() {
72 fmt.Print("\nNextTo index: ", it.Index())
73 fmt.Print("\nNextTo value: ", it.Value())
74 } /*
75 NextTo index: 1
76 NextTo value: "b"
77 NextTo index: 0
78 NextTo value: "a"
79 */
80
81 }