cs 106b, lecture 3 vector and grid - stanford university...example file, carroll.txt : 1 beware the...

26
CS 106B, Lecture 3 Vector and Grid reading: Programming Abstractions in C++, Chapter 4-5 This document is copyright (C) Stanford Computer Science and Ashley Taylor, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Marty Stepp, Chris Gregg, Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others

Upload: others

Post on 01-Nov-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

CS106B,Lecture3VectorandGrid

reading:ProgrammingAbstractionsinC++,Chapter4-5

Thisdocumentiscopyright(C)StanfordComputerScienceandAshleyTaylor,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyMartyStepp,ChrisGregg,KeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers

Page 2: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

2

Plan for Today • Learnabouttwonew"ADTs"orcollections

–  Vector:adatastructureforrepresentinglists– Grid:adatastructureidealforrepresentingtwodimensionalinformation

Page 3: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

3

STL vs. Stanford • collection:anobjectthatstoresdata;a.k.a."datastructure"

–  theobjectsstoredarecalledelements.–  Alsoknownas"ADTs"–abstractdatatypes

• StandardTemplateLibrary(STL):C++builtinstandardlibraryofcollections.– vector,map,list,...–  Powerfulbutsomewhathardtousefornewcoders(messysyntax)–take106L!

• StanfordC++library(SPL):CustomlibraryofcollectionsmadeforuseinCS106B/X.– Vector,Grid,Stack,Queue,Set,Map,...–  SimilartoSTL,butsimplerinterfaceanderrormessages.– Notethecapitalizedfirstletter

Page 4: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

4

Vectors (Lists) #include"vector.h"

• vector(akalist):acollectionofelementswith0-basedindexes–  likeadynamically-resizingarray(JavaArrayListorPythonlist)–  Includethetypeofelementsinthe<>brackets//initializeavectorcontaining5integers//index01234Vector<int>nums{42,17,-6,0,28};

Vector<string>names;//{}names.add("Ashley");//{"Ashley"}names.add("Shreya");//{"Ashley","Shreya"}names.insert(0,"Ed");//{"Ed","Ashley","Shreya"}

Page 5: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

5

Why not arrays? //actualarraysinC++aremostlyawfulintnums[5]{42,17,-6,0,28};//no

• Arrayshavefixedsizeandcannotbeeasilyresized.–  InC++,anarraydoesn'tevenknowitssize.(no.lengthfield)

• C++letsyouindexoutofthearraybounds(garbagememory)withoutnecessarilycrashingorwarning.

• Anarraydoesnotsupportmanyoperationsthatyou'dwant:–  inserting/deletingelementsintothefront/middle/backofthearray,reversing,sortingtheelements,searchingforagivenvalue...

index 0 1 2 3 4value 42 17 -6 0 28

Page 6: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

6

Vector members (5.1) v.add(value);orv+=value;orv+=v1,v2,...,vN;

appendsvalue(s)atendofvector

v.clear(); removesallelementsv[i]orv.get(i) returnsthevalueatgivenindexv.insert(i,value); insertsgivenvaluejustbeforethegivenindex,shifting

subsequentvaluestotherightv.isEmpty() returnstrueifthevectorcontainsnoelementsv.remove(i); removes/returnsvalueatgivenindex,shifting

subsequentvaluestotheleftv[i]=value;orv.set(i,value);

replacesvalueatgivenindex

v.subList(start,length) returnsnewvectorofsub-rangeofindexes

v.size() returnsthenumberofelementsinvector

v.toString() returnsastringrepresentationofthevectorsuchas"{3,42,-7,15}"

ostr<<v printsvtogivenoutputstream(e.g.cout<<v)

Page 7: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

7

Iterating over a vector Vector<string>names{"Ed","Hal","Sue"};for(inti=0;i<names.size();i++){cout<<names[i]<<endl;//forloop}//EdHalSuefor(inti=names.size()-1;i>=0;i--){cout<<names[i]<<endl;//forloop,backward}//SueHalEd

for(stringname:names){cout<<name<<endl;//"for-each"loop}//EdHalSue//Can'tedit(insert/delete)infor-eachloop

Page 8: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

8

Vector insert/remove v.insert(2,42);

• shiftelementsrighttomakeroomforthenewelement

v.remove(1);• shiftelementslefttocoverthespaceleftbytheremovedelement

(Theseoperationsareslowerthemoreelementstheyneedtoshift.)

index 0 1 2 3 4value 3 8 9 7 5

index 0 1 2 3 4 5value 3 8 42 9 7 5

index 0 1 2 3 4 5value 3 8 42 9 7 5

index 0 1 2 3 4value 3 42 9 7 5

Page 9: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

9

Announcements • Assignment0dueFriday

–  Fillouttheexamsurveyby5PMonFriday–  IfyouneedhelpwithQtstopbyLaIRorAshley'sofficehours(lastchancetogethelpis12:15PMonThursday)

• Sectionsstarttoday!Shouldhavereceivedanemailfromcs198@cs.stanford.edu–  Youcanswitchyoursectionorsignuplateatcs198.stanford.edu–  EmailShreyaatshreya@cs.stanford.eduifyouwereassignedadifferentsectionthanyourpartner

Page 10: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

10

Grid (5.1) #include"grid.h"

•  likea2Darray,butmorepowerful• Goodforboardgames,matrices,images,citymaps,etc.• mustspecifyelementtypein<>(atemplateoratypeparameter)

//constructingaGridGrid<int>matrix(3,4);matrix[0][0]=75;...

//orspecifyelementsin{}Grid<int>matrix={{75,61,83,71},{94,89,98,100},{63,54,51,49}};

0 1 2 30 75 61 83 711 94 89 98 1002 63 54 51 49

row

column

Page 11: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

11

Grid members (5.1)* Grid<type>name(r,c);Grid<type>name;

creategridwithgivennumberofrows/cols;empty0x0gridifomitted

g[r][c]org.get(r,c) returnsvalueatgivenrow/colg.fill(value); seteverycelltostorethegivenvalueg.inBounds(r,c) returnstrueifgivenpositionisinthegridg.numCols()org.width() returnsnumberofcolumnsg.numRows()org.height() returnsnumberofrowsg.resize(nRows,nCols); resizesgridtonewsize,discardingoldcontentsg[r][c]=value;org.set(r,c,value);

storesvalueatgivenrow/col

g.toString() returnsastringrepresentationofthegridsuchas"{{3,42},{-7,1},{5,19}}"

ostr<<g prints,e.g.{{3,42},{-7,1},{5,19}}

*(apartiallist;seehttp://stanford.edu/~stepp/cppdoc/)

Page 12: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

12

Looping over a grid • Row-majororder:

for(intr=0;r<grid.numRows();r++){for(intc=0;c<grid.numCols();c++){dosomethingwithgrid[r][c];}}

//"for-each"loop(alsorow-major)for(intvalue:grid){dosomethingwithvalue;}

• Column-majororder:for(intc=0;c<grid.numCols();c++){for(intr=0;r<grid.numRows();r++){dosomethingwithgrid[r][c];}}

0 1 2 3

0 75 61 83 71

1 94 89 98 91

2 63 54 51 49

0 1 2 3

0 75 61 83 71

1 94 89 98 91

2 63 54 51 49

Page 13: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

13

Grid as parameter • WhenaGridispassedbyvalue,C++makesacopyofitscontents.

–  Copyingisslow;youshouldpassbyreferencewith&–  Ifthecodewon'tmodifythegrid,alsopassitasconst

//Whichoneisbest?A)intcomputeSum(Grid<int>g){B)intcomputeSum(Grid<int>&g){C)intcomputeSum(constGrid<int>g){D)intcomputeSum(constGrid<int>&g){//Whichoneisbest?A)voidinvert(Grid<double>matrix){B)voidinvert(Grid<double>&matrix){C)voidinvert(constGrid<double>matrix){D)voidinvert(constGrid<double>&matrix){

Page 14: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

14

Grid exercise •  WriteafunctionknightCanMovethatacceptsagridandtworow/columnpairs(r1,c1),(r2,c2)asparameters,andreturnstrueifthereisaknightatchessboardsquare(r1,c1)thatcanlegallymovetoemptysquare(r2,c2).–  Recallthataknightmakesan"L"shapedmove,going2squaresinonedimensionand1squareintheother.

–  knightCanMove(board,1,2,2,4)returnstrue0 1 2 3 4 5 6 7

0 "king"

1 "knight"

2

3 "rook"

4

5

6

7

knightCanMove

Page 15: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

15

Grid exercise solution boolknightCanMove(Grid<string>&board,intr1,intc1,intr2,intc2){if(!board.inBounds(r1,c1)||!board.inBounds(r2,c2)){returnfalse;}

if(board[r1][c1]!="knight"||board[r2][c2]!=""){returnfalse;}

intdr=abs(r1-r2);intdc=abs(c1-c2);if(!((dr==1&&dc==2)||(dr==2&&dc==1))){returnfalse;}

returntrue;}

Page 16: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

16

Grid solution 2 boolknightCanMove(Grid<string>&board,intr1,intc1,intr2,intc2){intdr=abs(r1-r2),dc=abs(c1-c2);returnboard.inBounds(r1,c1)&&board.inBounds(r2,c2)&&board[r1][c1]=="knight"&&board[r2][c2]==""&&((dr==1&&dc==2)||(dr==2&&dc==1));}

Page 17: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

Overflow(extra)slides

Page 18: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

18

istringstream #include<sstream>

• Anistringstreamletsyoutokenizeastring.

//readspecificwordtokensfromastringistringstreaminput("JennySmith8675309");stringfirst,last;intphone;input>>first>>last;//first="Jenny",last="Smith"input>>phone;//8675309//readalltokensfromastringistringstreaminput2("Tobeornottobe");stringword;while(input2>>word){cout<<word<<endl;//To\nbe\nor\nnot\n...}

Page 19: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

19

ostringstream #include<sstream>

• Anostringstreamletsyouwriteoutputintoastringbuffer.– Usethestrmethodtoextractthestringthatwasbuilt.//produceaformattedstringofoutputintage=42,iq=95;ostringstreamoutput;output<<"Zoidberg'sageis"<<age<<endl;output<<"andhisIQis"<<iq<<"!"<<endl;stringresult=output.str();//result="Zoidberg'sageis42\nandhisIQis95!\n"

Page 20: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

20

Bug: Mix lines/tokens cout<<"Howoldareyou?";intage;cin>>age;

cout<<"Andwhat'syourname?";stringname;getline(cin,name);cout<<"Wow,"<<name<<"is"<<age<<"!"<<endl;//output://Howoldareyou:17//Andwhat'syourname:Stuart//Wow,is17!–  Advice:Don'tmixgetlineand>>onthesameinputstream.–  Advice:AlwaysuseStanfordgetXxxmethodstoreadfromcin.

userinput:

17\nStuart\n

Page 21: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

21

Exercise: inputStats2 • WriteafunctioninputStats2thatprintsstatisticsaboutthedatainafile.Examplefile,carroll.txt:

1BewaretheJabberwock,myson,2thejawsthatbite,theclawsthatcatch,34BewaretheJubJubbirdandshun5thefrumiousbandersnatch.

• ThecallofinputStats2("carroll.txt");shouldprint:

Line1:30chars,5wordsLine2:41chars,8wordsLine3:0chars,0wordsLine4:31chars,6wordsLine5:26chars,3wordslongest=41,average=25.6

inputStats2

Page 22: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

22

inputStats2 solution /*Printslength/countstatisticsaboutdatainthegivenfile.*/voidinputStats2(stringfilename){ifstreaminput;input.open(filename);intlineCount=0,longest=0,totalChars=0;stringline;while(getline(input,line)){lineCount++;totalChars+=line.length();longest=max(longest,line.length());intwordCount=countWords(line);//onnextslidecout<<"Line"<<lineCount<<":"<<line.length()<<"chars,"<<wordCount<<"words"<<endl;}doubleaverage=(double)totalChars/lineCount;cout<<longest="<<longest<<",average="<<average<<endl;}

Page 23: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

23

inputStats2 solution /*Returnsthenumberofwordsinthegivenstring.*/intcountWords(stringline){istringstreamwords(line);intwordCount=0;stringword;while(words>>word){wordCount++;}returnwordCount;}

Page 24: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

24

Formatted I/O #include<iomanip>

–  helpsproduceformattedoutput,alaprintf

for(inti=2;i<=2000;i*=10){//21.41cout<<left<<setw(4)<<i//204.47<<right<<setw(8)<<fixed//20014.14<<setprecision(2)<<sqrt(i)<<endl;//200044.72}

Membername Description

setw(n) right-alignsnexttokeninafieldncharswide

setfill(ch) setspaddingcharsinsertedbysetwtothegivenchar(default'')

setbase(b) printsfuturenumerictokensinbase-b

left,right left-orright-alignstokensifsetwisused

setprecision(d) printsfuturedoubleswithddigitsafterdecimal

fixed printsfuturedoubleswithafixednumberofdigits

scientific printsfuturedoublesinscientificnotation

Page 25: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

25

Exercise: Hours • Givenhours.txtofsectionleaderhoursworked,inthisformat:

1123Alex3241246Jessica8.51.55510637289Erik3644.684

• WritecodetooutputhoursworkedbyeachSLinthisformat:

Alex(ID#123)worked10.0hours(2.50/day)Jessica(ID#46)worked36.0hours(6.00/day)Erik(ID#7289)worked21.7hours(4.34/day)

hoursWorked

Page 26: CS 106B, Lecture 3 Vector and Grid - Stanford University...Example file, carroll.txt : 1 Beware the Jabberwock, my son, 2 the jaws that bite, the claws that catch, 3 4 Beware the JubJub

26

Hours solution /*Thisprogramcomputesthe...*/#include<fstream>#include<iomanip>#include<iostream>#include<sstream>usingnamespacestd;intmain(){ifstreaminput;input.open("hours.txt");stringline;while(getline(input,line)){//"7289Erik3644.684"istringstreamtokens(line);intid;//7289stringname;//"Erik"tokens>>id>>name;//restoftokensaredaysdoubletotalHours=0.0;intdays=0;...

doublehours;while(tokens>>hours){totalHours+=hours;days++;}//Erik(ID#7289)worked//21.7hours(4.34/day)cout<<left<<setw(9)<<name<<"(ID#"<<right<<setw(5)<<id<<")worked"<<fixed<<setprecision(1)<<totalHours<<"hours("<<setprecision(2)<<totalHours/days<<"/day)"<<endl;}return0;}