Your updated code was much easier to compile without line numbers, but it lacked package and import instructions.
Looking at my code, I noticed a few things. Here is my revised version of your code.
package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" "container/vector" ) func main() { n := scanf(os.Stdin) fmt.Println() fmt.Println(len(n), n) } func scanf(in io.Reader) []int { var nums vector.IntVector rd := bufio.NewReader(os.Stdin) str, err := rd.ReadString('\n') for err != os.EOF { fields := strings.Fields(str) for _, f := range fields { if i, err := strconv.Atoi(f); err == nil { nums.Push(i) } } str, err = rd.ReadString('\n') } return nums }
I can use any input file for scanf() , not just Stdin ; scanf() takes io.Reader as a parameter.
You wrote: nums := new(vector.IntVector) , where type IntVector []int . This selects the whole slice reference called nums and initializes it to zero, then the new() function selects the whole slice reference and initializes it to zero, and then assigns it nums . I wrote: var nums vector.IntVector , which avoids redundancy by simply highlighting a link to an integer slice named nums and initializing it to zero.
You did not mark err for strconv.Atoi() , which meant that invalid input was converted to a null value; I missed it.
To copy from a vector to a new slice and return the slice, you wrote:
r := make([]int, nums.Len()) for i := 0; i < nums.Len(); i++ { r[i] = nums.At(i) } return r
First, I just replaced this with the equivalent IntVector.Data() method: return nums.Data() . Then I took advantage of the fact that type IntVector []int and avoided highlighting and copying by replacing it with: return nums .
peterSO
source share