0% found this document useful (0 votes)
14 views

Module 03

Uploaded by

Diamond
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module 03

Uploaded by

Diamond
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module M03

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outline
Module M03: Arrays and Strings

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors
Partha Pratim Das

N
Strings
Concatenation
More operations
Department of Computer Science and Engineering
string.h
string class
Indian Institute of Technology, Kharagpur
Module Summary [email protected]

All url’s in this module have been accessed in September, 2021 and found to be functional

Programming in Modern C++ Partha Pratim Das M03.1


Module Recap

Module M03

• Understanding differences between C and C++ for:

L
Partha Pratim
Das
◦ IO

E
Objectives &
Outline ◦ Variable declaration
◦ Standard Library

T
Arrays and
vectors
Fixed Size Array
◦ bool

P
Arbitrary Size Array
vectors • C++ gives us more flexibility in terms of basic declaration and input / output

N
Strings
Concatenation
• Many C constructs and functions are simplified in C++ which helps to increase the
More operations ease of programming
string.h
string class

Module Summary

Programming in Modern C++ Partha Pratim Das M03.2


Module Objectives

Module M03

• Understand array usage in C and C++

L
Partha Pratim
Das
• Understand vector usage in C++

E
Objectives &
Outline • Understand string functions in C and string type in C++

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors

N
Strings
Concatenation
More operations
string.h
string class

Module Summary

Programming in Modern C++ Partha Pratim Das M03.3


Module Outline

Module M03

L
Partha Pratim
Das 1 Arrays & vectors
Array Implementations for fixed size array

E
Objectives &
Outline
Array Implementations for arbitrary sized array

T
Arrays and
vectors vectors in C++
Fixed Size Array

P
Arbitrary Size Array
vectors
2 C-Style Strings and string type in C++

N
Strings
Concatenation Concatenation of strings
More operations
string.h
More string operations
string class string.h
Module Summary
string class

3 Module Summary

Programming in Modern C++ Partha Pratim Das M03.4


Arrays and vectors

Module M03

L
Partha Pratim
Das

E
Objectives &
Outline

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors

N
Strings
Concatenation
More operations
string.h
string class

Module Summary
Arrays and vectors

Programming in Modern C++ Partha Pratim Das M03.5


Program 03.01: Fixed Size Array

Module M03 C Program C++ Program

L
Partha Pratim // Array_Fixed_Size.c // Array_Fixed_Size_c++.cpp
Das
#include <stdio.h> #include <iostream>

E
Objectives &
Outline int main() { int main() {
short age[4]; short age[4];

T
Arrays and
vectors
Fixed Size Array
age[0] = 23; age[0] = 23;

P
Arbitrary Size Array
age[1] = 34; age[1] = 34;
vectors age[2] = 65; age[2] = 65;
age[3] = 74; age[3] = 74;

N
Strings
Concatenation
More operations
printf("%d ", age[0]); std::cout << age[0] << " ";
string.h printf("%d ", age[1]); std::cout << age[1] << " ";
string class printf("%d ", age[2]); std::cout << age[2] << " ";
printf("%d ", age[3]); std::cout << age[3] << " ";
Module Summary

return 0; return 0;
} }

23 34 65 74 23 34 65 74

• No difference between arrays in C and C++

Programming in Modern C++ Partha Pratim Das M03.6


Program 03.02: Fixed size large array in C

Module M03 Hard-coded Using manifest constant

L
Partha Pratim // Array_Large_Size.c // Array_Macro.c
Das
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>

E
Objectives &
Outline #define MAX 100

T
Arrays and
vectors
int main() { int arr[100], sum = 0, i; int main() { int arr[MAX], sum = 0, i;
Fixed Size Array
printf("Enter no. of elements: "); printf("Enter no. of elements: ");

P
Arbitrary Size Array
int count; int count;
vectors scanf("%d", &count); scanf("%d", &count);

N
Strings
Concatenation
for(i = 0; i < count; i++) { for(i = 0; i < count; i++) {
More operations
arr[i] = i; arr[i] = i;
string.h sum + = arr[i]; sum + = arr[i];
string class } }
printf("Array Sum: %d", sum); printf("Array Sum: %d", sum);
Module Summary
} }

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• Hard-coded size • Size by manifest constant


Programming in Modern C++ Partha Pratim Das M03.7
Arbitrary Size Array

Module M03
This can be implemented in C (C++) in the following ways:

L
Partha Pratim
Das
• Case 1: Declaring a large array with size greater than the size given by users in all

E
Objectives &
Outline
(most) of the cases
◦ Hard-code the maximum size in code

T
Arrays and
vectors
Fixed Size Array
◦ Declare a manifest constant for the maximum size

P
Arbitrary Size Array
vectors • Case 2: Using malloc (new[]) to dynamically allocate space at run-time for the array

N
Strings
Concatenation
More operations
string.h
string class

Module Summary

Programming in Modern C++ Partha Pratim Das M03.8


Program 03.03: Fixed large array / vector
C (array & constant) C++ (vector & constant)
Module M03

// Array_Macro_c.c // Array_Macro_c++.cpp

L
Partha Pratim
Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <vector>

E
Objectives & using namespace std;
Outline
#define MAX 100 #define MAX 100

T
Arrays and
vectors int main() { int arr[MAX]; int main() { vector<int> arr(MAX); // Define-time size
Fixed Size Array
printf("Enter no. of elements: "); cout <<"Enter the no. of elements: ";

P
Arbitrary Size Array
int count, sum = 0, i; int count, sum = 0;
vectors
scanf("%d", &count); cin >>count;

N
Strings for(i = 0; i < count; i++) { for(int i = 0; i < count; i++) {
Concatenation
arr[i] = i; sum + = arr[i]; arr[i] = i; sum + = arr[i];
More operations
} }
string.h
printf("Array Sum: %d", sum); cout << "Array Sum: " << sum << endl;
string class
} }
Module Summary

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• MAX is the declared size of array • MAX is the declared size of vector
• No header needed • Header vector included
• arr declared as int [] • arr declared as vector<int>
Programming in Modern C++ Partha Pratim Das M03.9
Program 03.04: Dynamically managed array size

Module M03 C Program C++ Program

L
Partha Pratim // Array_Malloc.c // Array_Resize_c++.cpp
Das
#include <stdio.h> #include <iostream>
#include <stdlib.h> #include <vector>

E
Objectives &
Outline using namespace std;

T
Arrays and
vectors
int main() { printf("Enter no. of elements "); int main() { cout << "Enter the no. of elements: ";
Fixed Size Array
int count, sum = 0, i; int count, sum=0;

P
Arbitrary Size Array
scanf("%d", &count); cin >> count;
vectors
int *arr = (int*) malloc vector<int> arr; // Default size

N
Strings
Concatenation
(sizeof(int)*count); arr.resize(count); // Set resize
More operations
for(i = 0; i < count; i++) { for(int i = 0; i < arr.size(); i++) {
string.h arr[i] = i; sum + = arr[i]; arr[i] = i; sum + = arr[i];
string class } }
printf("Array Sum:%d ", sum); cout << "Array Sum: " << sum << endl;
Module Summary
} }

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• malloc allocates space using sizeof • resize fixes vector size at run-time
Programming in Modern C++ Partha Pratim Das M03.10
C-Style Strings and string type in C++

Module M03

L
Partha Pratim
Das

E
Objectives &
Outline

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors

N
Strings
Concatenation
More operations
string.h
string class

Module Summary
C-Style Strings and string type in C++

Programming in Modern C++ Partha Pratim Das M03.11


Strings in C and C++

Module M03
String manipulations in C and C++:

L
Partha Pratim
Das
• C-String and string.h library

E
Objectives &
Outline ◦ C-String is an array of char terminated by NULL
◦ C-String is supported by functions in string.h in C standard library

T
Arrays and
vectors
Fixed Size Array • string type in C++ standard library

P
Arbitrary Size Array
vectors ◦ string is a type

N
Strings ◦ With operators (like + for concatenation) it behaves like a built-in type
Concatenation
More operations ◦ In addition, for functions from C Standard Library string.h can be used in C++
string.h
string class
as cstring in std namespace
Module Summary

Programming in Modern C++ Partha Pratim Das M03.12


Program 03.05: Concatenation of Strings

Module M03 C Program C++ Program

L
Partha Pratim // Add_strings.c // Add_strings_c++.cpp
Das
#include <stdio.h> #include <iostream>
#include <string.h> #include <string>

E
Objectives &
Outline using namespace std;

T
Arrays and
vectors
int main() { char str1[] = {’H’,’E’,’L’,’L’,’O’,’ ’,’\0’}; int main(void) { string str1 = "HELLO ";
Fixed Size Array
char str2[] = "WORLD"; string str2 = "WORLD";

P
Arbitrary Size Array
char str[20];
vectors strcpy(str, str1);
strcat(str, str2); string str = str1 + str2;

N
Strings
Concatenation
More operations
printf("%s\n", str); cout << str;
string.h } }
string class

Module Summary
HELLO WORLD HELLO WORLD

• Need header string.h • Need header string


• C-String is an array of characters • string is a data-type in C++ standard library
• String concatenation done with strcat function • Strings are concatenated like addition of int
• Need a copy into str
• str must be large to fit the result
Programming in Modern C++ Partha Pratim Das M03.13
More Operations on Strings

Module M03
Further,

L
Partha Pratim
Das
• operator= can be used on strings in place of strcpy function in C

E
Objectives &
Outline • operator<=, operator<, operator>=, operator> operators can be used on strings
in place of strcmp function in C

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors

N
Strings
Concatenation
More operations
string.h
string class

Module Summary

Programming in Modern C++ Partha Pratim Das M03.14


Strings in C and C++: C Standard Library Functions
Function Description Used Frequently?
Module M03
Copying: memcpy Copy block of memory (function) Yes
memmove Move block of memory (function) Yes

L
Partha Pratim
Das strcpy Copy string (function) Yes
strncpy Copy characters from string (function)

E
Objectives &
Outline
Concatenation: strcat Concatenate strings (function) Yes
strncat Append characters from string (function)

T
Arrays and Comparison: memcmp Compare two blocks of memory (function)
vectors
strcmp Compare two strings (function) Yes
Fixed Size Array

P
Arbitrary Size Array
strcoll Compare two strings using locale (function)
vectors strncmp Compare characters of two strings (function)
strxfrm Transform string using locale (function)

N
Strings
Searching: memchr Locate character in block of memory (function) Yes
Concatenation
More operations
strchr Locate first occurrence of character in string (function) Yes
string.h strcspn Get span until character in string (function)
string class strpbrk Locate characters in string (function)
strrchr Locate last occurrence of character in string (function)
Module Summary
strspn Get span of character set in string (function)
strstr Locate substring (function) Yes
strtok Split string into tokens (function) Yes
Other: memset Fill block of memory (function)
strerror Get pointer to error message string (function)
strlen Get string length (function) Yes
Macros: NULL Null pointer (macro) Yes
Types: size t Unsigned integral type (type) Yes
Programming in Modern C++ Partha Pratim Das M03.15
Strings in C and C++: C++ Standard Library string Class

Module M03
• Strings are objects that represent sequences of characters
• The standard string class provides support for such objects with an interface similar to that of

L
Partha Pratim
Das
a standard container of bytes, but adding features specifically designed to operate with strings

E
Objectives &
Outline
of single-byte characters
• The string class is an instantiation of the basic string class template that uses char (that is,

T
Arrays and
vectors bytes) as its character type, with its default char traits and allocator types
Fixed Size Array

P
Arbitrary Size Array Function Description (Member Function) C Parallel
vectors Member functions

N
Strings (constructor) Construct string object (public) Initialize string object with a C string
Concatenation (destructor) String destructor (public)
More operations operator= String assignment (public) strcpy(). operator= does shallow copy
string.h Iterators Iteration done explicitly by loop index
string class begin Return iterator to beginning (public)
Module Summary end Return iterator to end (public)
rbegin Return reverse iterator to reverse beginning (public)
rend Return reverse iterator to reverse end (public)
cbegin Return const iterator to beginning (public)
cend Return const iterator to end (public)
crbegin Return const reverse iterator to reverse beginning (public)
crend Return const reverse iterator to reverse end (public)

Programming in Modern C++ Partha Pratim Das M03.16


Strings in C and C++: C++ Standard Library string Class
Function Description (Member Function) C Parallel
Module M03
Capacity
size Return length of string (public) strlen()

L
Partha Pratim
Das length Return length of string (public) strlen()
max size Return maximum size of string (public) Fixed at allocation

E
Objectives & resize Resize string (public)
Outline
capacity Return size of allocated storage (public) Need to be remembered in the code

T
Arrays and reserve Request a change in capacity (public)
vectors
clear Clear string (public) strcpy() an empty string
Fixed Size Array

P
empty Test if string is empty (public) strlen() == 0
Arbitrary Size Array
vectors
shrink to fit Shrink to fit (public)
String operations

N
Strings
c str Get C string equivalent (public) C string from a string object
Concatenation
data Get string data (public)
More operations
string.h
get allocator Get allocator (public)
string class copy Copy sequence of characters from string (public) strncpy()
find Find content in string (public) strchr(), strstr()
Module Summary
rfind Find last occurrence of content in string (public)
find first of Find character in string (public) strchr()
find last of Find character in string from the end (public) strrchr()
find first not of Find absence of character in string (public)
find last not of Find non-matching character in string from the end (public)
substr Generate substring (public) strncpy()
compare Compare strings (public) strcmp()

Programming in Modern C++ Partha Pratim Das M03.17


Strings in C and C++: C++ Standard Library string Class
Function Description (Member Function) C Parallel
Module M03
Element access
operator[] Get character of string (public) operator[]

L
Partha Pratim
Das at Get character in string (public) operator[]
back Access last character (public) Character at strlen()-1

E
Objectives &
Outline
front Access first character (public) Character at 0th location
Modifiers

T
Arrays and
vectors
operator+= Append to string (public) strcat()
Fixed Size Array
append Append to string (public) strcat()

P
Arbitrary Size Array
push back Append character to string (public) Set character to strlen() and NULL to next location t
vectors assign Assign content to string (public)
insert Insert into string (public)

N
Strings
Concatenation
erase Erase characters from string (public)
More operations
replace Replace portion of string (public)
string.h swap Swap string values (public) Character by character swapping between two arrays
string class pop back Delete last character (public) Set location strlen()-1 to NULL
Member constants
Module Summary
npos Maximum value for size t (public static)
Non-member function overloads
operator+ Concatenate strings (global) strcat()
relational operators Relational operators for string (global) strcmp() followed by tests for -1, 0, +1
swap Exchanges the values of two strings (global)
operator>> Extract string from stream (global) format %s
operator<< Insert string into stream (global) format %s
getline Get line from stream into string (global) getline() in <stdlib.h>
Programming in Modern C++ Partha Pratim Das M03.18
Module Summary

Module M03

• Working with variable sized arrays is more flexible with vectors in C++

L
Partha Pratim
Das
• String operations are easier with C++ standard library

E
Objectives &
Outline

T
Arrays and
vectors
Fixed Size Array

P
Arbitrary Size Array
vectors

N
Strings
Concatenation
More operations
string.h
string class

Module Summary

Programming in Modern C++ Partha Pratim Das M03.19

You might also like