IT計(jì)算機(jī) primitive(原始的)_第1頁(yè)
IT計(jì)算機(jī) primitive(原始的)_第2頁(yè)
IT計(jì)算機(jī) primitive(原始的)_第3頁(yè)
IT計(jì)算機(jī) primitive(原始的)_第4頁(yè)
IT計(jì)算機(jī) primitive(原始的)_第5頁(yè)
已閱讀5頁(yè),還剩89頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

Chapter6

Cb/XCA,,S葉,Pro0grammingD

DataTypesLanguages

SIXTHEDITION

RobertW.Sebesta

PEARSON

Afklison

Copyrightc2004PiurwaAddHon-Wrdry.?MIright*mrnvd.ISBN0-321-19362-8

Chapter6Topics

?Introduction

?PrimitiveDataTypes

?CharacterStringTypes

?User-DefinedOrdinalTypes

?ArrayTypes

?AssociativeArrays

?RecordTypes

?UnionTypes

?PointerTypes

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-2

Introduction

?ThisChapterintroducestheconceptof

adatatypeanddiscusses:

-Characteristicsofthecommonprimitive(原始的)

datatypes.

-Characterstrings

一Userdefineddata-types

-Designofenumerations(歹u聚)andsub-rangedata

types

-Designofstructureddatatypesincludingarrays,

records,unionsandsettypes.Heap堆稹

在相郝信者存軍元中存放資料,

-Pointersandheapmanagement很像一槿堆疊操作。

但是,堆稹指上票保持指向

堆稹的第一彳固罩元,而不是

下一他可用的堆疊罩元。

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-3

DataType

?Adatatypedefinesacollectionofdataobjects

andasetofpredefinedoperationsonthose

objects

?EveryPLneedsavarietyofdatatypesinorder

tobettermodel/matchtheworld

?Moredatatypesmakesprogrammingeasierbut

toomanydatatypesmightbeconfusing

?Whichdatatypesaremostcommon?Which

datatypesarenecessary?Whichdatatypesare

uncommonyetuseful?

?HowaredatatypesimplementedinthePL?

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-4

EvolutionofDataTypes

?FORTRANI

-INTEGER,REAL,arrays

?COBOL

-Programmerscouldspecifyaccuracyofdecimal

-Introducedstructureddatatypesforrecords

?PL/I

-Extendedaccuracyspecificationtointegerandfloating-

point

?ALGOL68

-User-defineddatatypes

?Ada83

-Usercancreateuniquetypesforeveryclassofvariables

andthesystemenforces渤行)theuniquenessofthe

types.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-5

Descriptors

?Adescriptoristhecollectionofattributes

ofavariable

?Inanimplementation,adescriptoristhe

collectionofmemorycellsthatstore

variableattributes(燮數(shù)的腐性)

-Ifallattributesarestatic,thedescriptoris

requiredonlyatcompiletime

-Ifattributesaredynamic,partorallofthe

descriptormustbepresentduringexecution

-Inallcases,descriptorsareneededfor

?Typechecking

?Allocationanddeallocation信己意||的配置典解除)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-6

EvolutionofDataTypes

?DesignIssuesforalldatatypes:

-Whatisthesyntaxofreferencestovariables?

一Whatoperationsaredefinedandhowarethey

specified?

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-7

Primitivedatatypes

?Aprimitivedatatypeisonethatisnotdefinedin

termsofothertypes

?Often,primitivetypesareareflectionofthe

underlyinghardware:

-Integer

-Floatingpoint

?Otherprimitivetypesrequirealittlenon-hardware

supportfortheirimplementation,Majorcategories

include

-Numeric(數(shù)彳直)

-Boolean(布林彳直)

-Character(字元)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-8

PrimitiveDataTypes

.:-Integer:ShortInt,Integer;LongInt(etc)

:-FloatingPoint:Real,DoublePrecision

Storedin3parts,signbit,exponentand

mantissa(seefig6.1)

-Decimal:BinaryCodedDecimal,BCD

(COBOL,C#,2digitsperbyte)

usedinbusinesslanguageswithasetdecimal

fordollarsandcents

-Boolean:(TRUE/FALSE,1/0,YES/NO)

':-Character:UsingEBCDIC,ASCII,UNICODE,

etC.Mantissa尾數(shù)

由已知浮黑占數(shù)中的最高有效數(shù)位

系且成的定黑占數(shù)。浮黑占表示法中,

指一數(shù)值的小數(shù)部分。封數(shù)表示

法中,指非負(fù)值的小數(shù)部分。

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-9

Numerictypes

?Integer:ShortInt,Integer,LongInt(etc)

-Almostalwaysanexactreflectionofhardware

?Twoscomplement件甫敷)tosavenegativeintegers,

whichisconvenientforadditionandsubtraction.

Intwos<omplementnotation,therepresentationofa

negativeintegerisformedbytakingthelogical

complementofthepositiveversionofthenumber

andaddingone.

?Chas8differentintegertypesbycombining

-char,short,int,long

一signedandunsigned

?AdaallowsSHORTINTEGER,INTEGER,LONG

-Somelanguagessupportintegersofunlimited

magnitude(implementedinsoftware)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-10

Numerictypes

Floating-point:Real,DoublePrecision

-Storedin3parts,signbit,exponentandmantissa(尾數(shù))

-Modelrealnumbers,butareonlyapproximations

-Valuesaredefinedintermsofprecisionandrange

?Precisionistheaccuracyofthefractionalpart(小數(shù)部份)

?Rangeisacombinationoftherangeoffractionsand

exponents

?Adaexamples:

typeSPEEDisdigits7range0.0..1000.0;

typeVOLTAGEisdelta0.1range-0.0..5.0;

-Hardwaresupport:IEEEFloating-Point

Standard754:

?Singleprecision:32bits

-Signbit,8-bitexponent,23bitsignificand

?Doubleprecision:64bits

-Signbit,11-bitexponent,52bitsignificand

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-11

IEEEFloatingPointStandard

?Singleprecision:32bitrepresentationwith1bit

sign,8bitexponent,23bitmantissa

?Doubleprecision:64bitrepresentationwith1bit

sign,11bitexponent,52bitmantissa

8bits23bits

ExponentFraction

tSignbit

Mantissa尾數(shù)

(a)由已知浮黑占數(shù)中的最高有效數(shù)位

系且成的定黑占數(shù)。浮黠表示法中,

指一數(shù)值的小數(shù)部分。卦數(shù)表示

,法中,指非負(fù)值的小數(shù)部分。

11bits52bits

ExponentFraction

tsignbit

(b)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-12

Numerictypes

?Decimal(十迤制)

-Usedmostlyforbusinessapplications

-Storesafixednumberofdecimaldigits,withthe

decimalpointatafixedposition

-Decimaldigitsarecoded(BinaryCodedDecimal,BCD

with2digitsperbyte,e.g.COBOL,C#)

-Arecapableofpreciselystoringdecimalvalueswithina

restrictedrange,especially,usedinbusinesslanguages

withasetdecimalfordollarsandcents

-Operationsaredoneinhardwareonmachinesthat

supportit;insoftwareonthosethatdonot

-ExamplefromPL/I:

DCLPAYRATEFIXEDDECIMAL(7,2);

-Advantage:accuracy

-Disadvantages:\\mtedrange,wastesmemory

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-13

BooleanTypes

?Simplestofalltypes

?Rangeofvalueshasonly2elements,trueand

false

?IntroducedinALGOL60

?Couldberepresentedasasinglebit,butmost

oftenasabyte(thesmallestefficiently

addressablecellofmemory)

?CdoesdonotincludeaBooleantype;instead,

numericexpressionsareusedasconditionals

?Advantage:readability

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-14

CharacterStrings

?Charactersareanotherprimitivedatatypewhichmapeasily

intointegers.Characterdataarestoredasnumericcodings

-ASCII

?8-bitallows256characters

?Inadequate(不遹)forglobalcommunication

-Unicode

?16-bitallows655536characters

?Includescharsctersfrommostoftheworld'snatural

languages

?Neededascomputersbecomelesseurocentric(西方的)to

representthefullrangeofnon-romanalphabetsand

pictographs(象形文字).

?Javawasthefirstwidely-usedlanguagetousetheUnicode

characterset

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-15

Characterstringtypes

?Valuesareasequenceofcharacters

?Designissues:

-Ischaracterstringaprimitivetypeorjustaspecial

kindofarray?

-Isthelengthofcharacterstringobjectsstaticor

dynamic?

?Operationsoncharacterstrings:

-Assignment

-Comparison(=,>,etc.)

-Concatenatione.g.(Ada)N:=N1&N2(字串結(jié)合)

-Substringreferencee.g.(Ada)N(2..4)

-Patternmatching

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-16

CharacterstringsinAda

-STRINGisasomewhatprimitivetype

-STRINGisatypethatispredefinedasaone-

dimensionalarrayofCHARACTERelements:

S:STRING(l.-lO);

一Operationsinclude

?Substringreference:S(1..3)="Bob";

?Concatenation:S:="Bob"&"Alooga";

?Comparison:=,/=,<,<=,>,>=

-StringshavefixedlengthinAda

Concatenation512置

按規(guī)定的次序把雨他I字串結(jié)合篇一彳固

字串的一槿操作,所橫成字串的畏度

等於甬彳固字串畏度之和。

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-17

Characterstrings

inCandC++

一Notaprimitivetype

-chararraysstorecharacterstrings

I一Stringsareterminatedby、\0'->stringshave

limiteddynamiclength

-Thestandardlibrarystring.hincludesa

collectionofstringoperations,whichinclude

?strlen(stringlength)

■MffX?strcat(stringconcatenation)

?strcmp(stringcomparison)

?strcpy(stringcopy)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-18

CharacterstringsinJava

一Stringsareimplementedby2classes

?String—valuesareconstantstrings

?StringBuffer—valuesarechangeable

一Objectswhichareimmutable(tochangethe

length,youhavetocreateanewstringobject)

and+istheonlyoverloadedoperatorfor

string(concat),nooverloadingfor<,>,etc

一Operationsareprovidedviaclassmethods:

一Example:

Stringsi,s2,s3;

si="BobAlooga”;

s2=si+)Jr/7;

s3=sl.substring(0,3);

intp=sl.indexOfCAK');//p=4

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-19

Characterstringsinothers

?Perl

-Patternsaredefinedintermsofregularexpressions

providingaverypowerfulfacility!

-Patternforidentifier:/[A-Za-z][A-Za-z\d]+/

-Patternfornumericliteral:/\d+\.?d*|\.\d+/

?SNOBOL4

-Theultimatestringmanipulationlanguage

-Stringisaprimitivetype

-Therearemanystringmanipulationoperations,

includingegborage信辛翥的)pattern-matching

?StringsinPerl,LISPandSNOBOL4have

dynamiclength.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-20

Characterstringsinothers

?FORTRAN77/90,COBOL,Ada-static

lengthstrings

e.g.InFORTRAN90

CHARACTER(LEN=15)NAME;

?PL/I,Pascal-variablelengthwithstatic

fixedsizestrings

?Somelanguages,e.g,Snobol,PerlandTel,

haveextensivebuilt-insupportforstrings

andoperationsonstrings.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-21

Evaluationofcharacterstring

?Characterstringsareimportanttothe

writabilityofalanguage.

?Dealingwithstringsasarraysmore

cumbersome(黃隹慮理的)thandealingwitha

primitivestringtype.

?Ifimplementedasaprimitivetypewith

staticlength,theyareinexpensive.Thus,

itisdifficulttojustifytheiromission.

?Dynamic-lengthstringsprovideadditional

flexibility,butaremoreexpensiveto

implement.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-22

Implementingcharacterstrings

?Staticlengthstrings

-Requireadescriptoronlyatcompiletime:

?Length(incharacters)

?Address(ofthefirstcharacter)

?Limiteddynamiclengthstrings

-Needaruntimedescriptorthatstores:

?Fixedmaximumlength

?Currentlength

?Addressoffirstcharacter

-CandC++stringsdonotrequirearun-timedescriptor

becausetheendofastringismarkedwiththenull

character

?Neitherstaticlengthnorlimiteddynamiclength

stringsrequireruntimestoragemanagement.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-23

descriptorcharacterstrings

Limiteddynamicstring

Maximumlength

Currentlength

Address

Compile-timeRun-timedescriptor

descriptorforstaticforlimiteddynamic

stringsstrings

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-24

Implementingcharacterstrings

?Dynamic-lengthstringsrequiremorecomplex

storagemanagement.

?2approaches:linked時(shí)速系吉串列,^表(二訕海.)

_Linkedlist一系且資料元素目的集合‘其J嗔序排列方法是使

-每他項(xiàng)目包含下一偃P嗔目在重月窗存信者器中的位址。

?Advantage:

-Allowsnewlyrequiredcellstocomefrom

anywhereintheheap

?Drawbacks(不利脩件):

-Storageoccupiedbylinks

-Someoperationsareslowedbythisrepresentation

-Storecompletestringsinadjacentcells(相鄢倨者存格)

?Advantage:

-Operationsarefaster

?Drawbacks:

-Whenstringgrowstheruntimesystemmustfinda

largeenoughblockofadjacentcells

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-25

User-definedordinaltypes

?Anordinaltypeisoneinwhichtherangeof

possiblevaluescanbeeasilyassociatedwiththe

setofnonnegativeintegers

?Twocommonlyimplementedordinaltypes

一Enumeration(歹f]聚)type

?oneinwhichtheuserenumeratesallthepossible

values,whicharenamedsymbolicconstants

?CanbeusedinFor-loops,casestatements,etc.

?UsuallycannotbeI/Oeasily

?Mainlyusedforabstraction/readabiIity

ExampleinC#

enumdays{Mon,Tue,Wed,Thu,Fri,Sat,Sun};

0,1,2,3,4,5,6

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-26

CandC++enumerationtypes

?Enumerationvaluesareimplicitlyconverted

tointeger.

?Namescannotbereusedwithsamescope

?Enumerationvaluesaresubjecttotherules

governingintegers.

?C++example:

enumcolortype{red,blue,green,yello,black);

colortypemyColor=blue,yourColor=red;

myColor++;wouldassigngreentomyColor.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-27

Pascalenumerationtypes

?Enumerationtypescanbeusedfor

-Arraysubscripts

-Forstatementvariables

-Casestatementselectors

?Cannotbeinputoroutput

?Namescannotbereusedinotherenumeration

types

?Pascalenumerationexample

typecolortype=(red,blue,green);

varcolor:colortype;

■■■

color:=blue;

ifcolor>red...

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-28

Adaenumerationtypes

、?CanbeusedasinPascal

?Canbeinput/output(viaEnumeration_IO).

?Namescanbereused;disambiguationis

accomplishedbycontextorbyusing

type_namez

?Example:

鼠弋]typeDAYSis(MonzTue,WedzThuzFri,Sat,Sun);

0*typeWEEKDAYSis(MonJue,Wed,ThuzFri);

today,tomorrow:Day;

■■■

MflwforDayinWEEKDAYSloop...

JMSforDayinDAYSTue..DAYSTriloop...

today:=DAYSTREDftomorrow);

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-29

Javaenumerationtypes

?Javadoesnotincludeanenumerationtype

?Enumerationtypesareclassesthatimplement

theEnumerationinterface

Classcolors{

Publicfinalintred=0;

Publicfinalintblue=1;

)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-30

User-definedordinaltypes

一Subrangetype:acontiguous(!?近的)

subsequenceofanordinaltypes

?Limitsalargetypetoacontiguoussubsequenceof

valueswithinthelargerrange

?providingadditionalflexibilityinprogrammingand

readability/abstraction

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-31

Subrangetypes

?Pascal:

type

uppercase=

index=1..100;

?Ada:

subtypeWEEKDAYSisDAYSrangeMon..Fri;

subtypeINDEXisINTEGERrange1..100;

-Note:WEEKDAYSiscompatiblewithDAYS

INDEXiscompatiblewithINTEGER

-Ada'sderivedtypeisdifferentfromsubtype:

typeINDEX2isnewINTEGERrange1..100;

-notcompatiblewithINTEGERorINDEX

?Asisthecasewithenumerationtypes,

subrangetypesaidreadabilityandreliability.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-32

Implementingordinaltypes

?Enumerationtypesareimplementedas

integers,withthefirstvaluerepresented

as0,thenextvalueas1,etc,

?Thepermittedoperationsaredifferent

fromthoseofinteger.

?Subrangetypesareimplementedusing

theparenttypewithcodeinsertedbythe

compilertorestrictassignmentto

subrangevariables.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-33

Evaluationofenumerationtypes

Aidtoefficiency-e.g.,compilercanselectand

useacompactefficientrepresentation(e.g,,

smallintegers)

Aidtoreadability-Symbolicconstantsare

mucheasiertounderstandandrememberthan

integerliterals(e.g,,noneedtocodeacoloras

anumber)

Aidtomaintainability-e.g,zaddinganew

colordoesn'trequireupdatinghard-coded

constants.

Aidtoreliability-eg,compilercancheck

operationsandrangesofvalue.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-34

Arraytypes

?Anarrayisahomogeneousaggregate(聚集)of

dataelementsinwhichanelementisidentified

byitspositionintheaggregate,relativetothe

firstelement

?Referencestoelementsincludeoneormore

subscripts

?Referencesrequirearuntimecomputationto

determinethelocationbeingreferenced

?Arraytypesareimplementedinmost

programminglanguages

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-35

Arraytypes

?Designissues

一Whattypesarelegalforsubscripts?

一Aresubscriptexpressionsrangechecked?

一Whenaresubscriptrangesbound?

一Whendoesallocationtakeplace?

一Whatisthemaximumnumberofsubscripts?

一Canarraysbeinitializedwhentheyhavetheir

storageallocated?

-Arearrayslicesallowed?

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-36

ArraysandIndexes

?Indexingisamappingfromindicestoelementsin

anarray:

map(arrayName,indexValue)—>arrayelement

?Syntaxofindexingisfairlyuniversal:

arraynamefollowedbylistofindices,

eachsurroundedbyparenthesesorbrackets

-Ada,FORTRAN,PL/Iuseparentheses:()

-Otherlanguagesusebrackets:[]

?Subscripttypes

-FORTRAN,C,C++,andJavaallowintegersubscriptsonly

-Pascalallowsanyordinaltype

(int,boolean,char,enum)

-Adaallowsintegerorenumeration(歹U聚)types

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-37

Fourcategoriesofarrays

?4categoriesofarraysbasedonsubscriptrange

bindingandstoragebinding:

-Static

-Fixedstackdynamic

-Stackdynamic

-Heapdynamic

?Insomelanguagesthelowerboundofthe

subscriptrangeisimplicit

-C,C++,Java—fixedat0

-FORTRAN—fixedat1

-Otherlanguagesrequireprogrammertospecifythe

subscriptrange.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-38

Staticarrays

?Staticarraysarethoseinwhich

一Rangeofsubscriptsisstaticallybound

一Storagebindingsarestatic

?Advantage:executionefficiencysinceno

dynamicallyallocation/deallocationis

required

?FORTRANarraysandsomearraysinAda

arestatic

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-39

Fixedstack-dynamicarrays

?Fixedstack-dynamicarraysarethosein

which

-Subscriptrangesarestaticallybound

-Allocationisdoneatdeclarationelaborationtime

?Advantageisspaceefficiency

-Storageisallocatedonlywhileblockinwhicharrayis

declaredisactive.

-Storageforlargearraysin2differentprocedurescan

besharedaslongasbotharenotactive

simultaneously

?PascallocalarraysandClocalarraysthat

arenotstaticarefixedstack-dynamic

arrays

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-40

Stack-dynamicarrays

?Astack-dynamicarrayisoneinwhich

-Subscriptrangesaredynamicallybound

-Storageallocationisdoneatruntime

-Bothremainfixedduringthelifetimeofthevariable

?Advantage:flexibility

?Adahasthiskindofarray:

declare

ARR:array(l..N)ofINTEGER;

begin

■■■

end;

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-41

Heap-dynamicarrays

?Aheap-dynamicarrayisoneinwhich

-Subscriptrangebindingisdynamic

-Storageallocationisdynamic

-Eithercanchangeanynumberoftimesduringexecution

?Arrayscangrowandshrinkastheneedarises

?FORTRAN90hasdynamicarrays:

INTEGER,ALLOCATABLE,ARRAY%:)::MAT

ALLOCATE(MAT(10,20))

DEALLOCATE(MAT)

?CandC++allowdynamicarraysvia

-mallocandfree

-newanddelete

?APLandPerlarrayschangesizesasneeded

?Javaarraysareobjects(heapdynamic)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-42

Numberofsubscripts

Arraydimensions

?FORTRANI

一Allowedupto3subscripts

?FORTRAN77

一Allowsupto7subscripts

?C,C++,Java

-limitedto1butarrayscanbenested

(i,e.arrayelementisanarray)allowing

foranynumberofdimensions

?Otherslanguages

一Nolimitisspecified

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-43

Arrayinitialization

FORTRAN:initializationatthetimestorageisallocated

INTEGERLIST⑶

DATALIST/10,20,30/

C,C++:lengthofarrayisimplicitbasedonlengthof

initializationlist

intlist[]={10,20,30);

charname[]=''bob";

char*names[]={''bob",〃sue”,〃tom〃};

Java

String[]names={''bob","sue","tom2;

AdadikeCbutyoucanspecifywhicharrayelementsare

assignedvalues(insteadofassigningallvalues)

LIST:array(1..5)ofINTEGER:=(1,2,3,4,5);

LIST2:array(l?10)ofINTGEGER:=

(1=>10,2..5=>100,others=>0);

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-44

ArrayOperations

?APLhasmanyarrayoperations:

-+,?,*,/forvectors,matrices,andscalars

-Unaryoperatorsforreversingvectors,columnsorrows

ofmatrices

-Transposeorinvertamatrix

?Ada

-Array-arrayassignment

-Concatenationforany1-dimensionalarraytype

-Relationaloperators(=and/=)

?CandC++

-Notmuchinthewayofarrayoperations

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-45

ArrayOperations

?Operationsthatapplytoanarrayasaunit(as

opposedtoasinglearrayelement)

?Mostlanguageshavedirectassignmentofone

arraytoanother(A:=B)ifbotharraysare

equivalent

?FORTRAN:AllowsarrayadditionA+B

?FORTRAN90:libraryofArrayopsincludingmatrix

multiplication,transpose

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-46

ArrayOperationsinJava

?InJava,arraysareobjects(sometimescalled

aggregatetypes)

?Declarationofanarraymayomitsizeasin:

-int[]arrayl;

-arraylisapointerinitializedtonil

-atalaterpoint,thearraymaygetmemory

allocateditaswith

-arrayl=newint[100];

?Arrayoperationsotherthanaccess(arrayl[2])are

throughmethodssuchasarrayl.length

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-47

Arrayslices

?Asliceissomesubstructureofanarray;

nothingmorethanareferencing

mechanism

?Examples:

-FORTRAN90

INTEGERMAT(1:4,1:4)

MAT(1:4,1)(1stcolumn)

MAT(2,1:4)(2ndrow)

一Ada

LIST(4..1O)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-48

ExampleslicesinFortran95

CUBE(2,1:3,1:4)CUBE(1:3,1:3,2:3)

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-49

Arrayimplementation

?Compile-timedescriptorfora

1-dimensionalarraymayinclude:

一Elementtype

一Indextype

一Indexlowerbound

一Indexupperbound

一Address

?Formulti-dimensionalarrays,information

abouteachindexrangemustbestored.

Copyright?2004PearsonAddison-Wesley.Allrightsreserved.6-50

Arrayimplementation

?Anaccessfunctionisusedtomaparray

subscriptstoaddresses.

?Fora1-dimensionalarray,theaccess

functionforarrayarris

address(arr[k])=

addr(arr[lower_bound])+(k-

lower_bound)*element_size

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論