Upload
beatrice-austin
View
214
Download
2
Embed Size (px)
DESCRIPTION
Array Examples cnt = 100;// not a const expr constexpr max = 100;// a const expr int array1[100];// good int array2[max];// good int array3[cnt];// error – not const int array4[getsize(something)]; // good iff getsize() is constexpr
Citation preview
Arrays, Vectors, and Strings
Allocation and referencing
Array Type
• Arrays are a compound type• Base_type name[size];
• Array dimension specifies the number of elements• Dimension must be a positive integer literal OR a constant expression (i.e., known at compile time)
Array Examples
cnt = 100; // not a const expr
constexpr max = 100; // a const expr
int array1[100]; // good
int array2[max]; // good
int array3[cnt]; // error – not const
int array4[getsize(something)];
// good iff getsize() is constexpr
Arrays
• Array indices run from 0 to Max-1• Always check your index!!
• Can reference element by index or by pointer dereference• A[i] or *(A + i)
• Type allows compiler to compute correct offset into memory
0xfa10
0xfa580xfa540xfa500xfa4c0xfa480xfa440xfa400xfa3c0xfa380xfa340xfa300xfa2c0xfa280xfa240xfa200xfa1c0xfa180xfa14
AddressRAM
0x00000004
int array1[5]={1,2,4,8,16};
char name[5]=“Mary”;
int *ptr = &array1[0];
0x000000020x00000001
0x000000080x00000010‘y’ ‘a’ ‘r’ ‘M’‘\0’ ‘\0’ ‘\0’ ‘\0’
Symbol Table
Identifier Type Locationarray1 int* 0xfa18name char* 0xfa2c
ptr int* 0xfa18
Note: null terminated
Arrays
2-D Arrays
• C++ does not really have multi-D arrays• Looks kind of like it: int A[M][N];
• Arrays are really pointers to the first element in a consecutively stored sequence of elements of same type• 2-D array is really pointer to a 1-D array of pointers to first row elements
C-Style Strings
• C++ has a String class• Can be referenced by index like array
• But it is a true object
• C strings are not a primitive type, nor are they a struct• A C-style string is just a 1-D array of char, with NULL termination
• NOTA BENE: always a '\0' at end!!!!
0xfa10
0xfa580xfa540xfa500xfa4c0xfa480xfa440xfa400xfa3c0xfa380xfa340xfa300xfa2c0xfa280xfa240xfa200xfa1c0xfa180xfa14
AddressRAM
0x00000004
char names[3]={“Julian”,
“James”,“John”};
0x000000020x00000001
0x000000080x00000010‘y’ ‘a’ ‘r’ ‘M’‘\0’ ‘\0’ ‘\0’ ‘\0’
Symbol Table
Identifier Type Locationarray1 int* 0xfa18name char* 0xfa2c
ptr int* 0xfa18
2-D Arrays
names char*[] 0xfa34
0x00000fa400x0000fa470x0000fa4d‘i’ ‘l’ ‘u’ ‘J’‘J’ ‘\0’ ‘n’ ‘a’‘s’ ‘e’ ‘m’ ‘a’‘h’ ‘o’ ‘J’ ‘\0’? ? ‘\0’ ‘n’
C-Style Strings and Chars
• Remember, char and string are not the same• 'a' is a char literal – uses one byte of RAM
• “a” is a string literal – uses two bytes of RAM
• Name[] = “Joe”; - uses... 4 bytes for the 3 characters plus null character
• Char *name – allocate pointer ONLY!!
• <strings.h> library – many functions
C String Library#include <strings.h>
i=strlen(p); // string length less nulli=strcmp(p1,p2); // neg if p1<p2, etc.p1=strcat(p1,p2); // appends p2 to p1p1=strcpy(p1,p2); // copies p2 to p1/*** WARNING – NO BOUNDS CHECKING! ***//* use these safe versions below! */i=strncmp(p1,p2,n); // … only up to np1=strncat(p1,p2,n); // … only up to np1=strncpy(p1,p2,n); // … only up to n
C String Library#include <strings.h>
size_t strlen(char s[])// not int!
int atoi(char s[]) // int value of s[]double atof(char s[]) // double valuelong atol(char s[]) // long valuevoid itoa(int val, char s[], int radix)
// converts integer value to string
C++ Strings
• C++ has string type
#include <string>using std::string;string s1; // default to emptystring s2=s1; // s2 is a *copy* of s1string s3=“Joe”; // s3 is copy of literalstring s4=(10,’c’); // s4 is cccccccccc
while (cin >> word) …// whitespace delimwhile (getline(cin, line)) … // \n delim
Strings & C-Stringsstring s(“Hello World”);
char *str=s; // error!const char *str = s.c_str(); // OK
/* Achtung! Contents of *str may change * Copy into local version if need * continued access to contents */
Use s.insert(), s.erase(), s.assign(),s.append(), and s.replace() on strings
Vectors
• Vectors very similar to arrays• Except they are class templates, not a type – must include type in declaration
• Take care of memory management
• Use push_back() to expand
Vector Initializationvector<double> dvec; // ivec emptyvector<int> ivec(10, 5); /* 10 ints
all 10 have value 5 */vector<int> ivec2(ivec); // copy ivecvector<int> ivec3 = ivec; // also copyvector<T> vec4(10);/* 10 item vector
of type T objs default init */vector<int> ivec5{2,3,5,7,11,13}
// 6 elements with values givenvector<int> ivec6 = {1,2,4,8,16}
// 5 elements with values given
Vector Initializationvector<int> ivec1(10);
vector<int> ivec2{10};
vector<int> ivec3(10, 5);
vector<int> ivec4{10, 5};
vector<string> sv1{“Al”,“Mo”, “Jo”};
vector<string> sv2(“Al”,“Mo”,“Jo”);
// 10 ints all value 0
// one int value 10
// 10 ints all value 5
// 2 ints, values 10 & 5
// list initialization
// error
Adding to a Vector
• Vector size may not be known• Vector may be large• Use push_back member functionvector<int> iv;for (int i=0; i != MAX; ++i) iv.push_back(i*i);vector<string> text;while (cin >> word) // word is string text.push_back(word);
Subscripting does not add elements!
Range For
• Auto type definition if unknown• Range for – like “foreach”
vector<int> iv2{1,2,3,4,5,6,7,8,9};for (auto &i=0 : iv2) // reference! i *= i; // square elements
for (auto i : iv2) // non-reference cout << i << endl;