Standard library types Practical session # 3 Software Engineering 094219

Preview:

Citation preview

Standard library types

Practical session # 3

Software Engineering 094219

Standard library The standard C++ library is a collection of

functions, constants, classes, objects and templates.

Extends the C++ language providing basic functionality to perform several tasks, like classes to interact with the operating system, data containers, manipulators to operate with them and algorithms commonly needed.

Further information can be found in: http://www.cplusplus.com/

BLACK BOX2

Agenda

vector and iterator

string

3

vector

vector is a sequential container similar to an array. Further information in :

http://www.cplusplus.com/reference/stl/vector/

vector is a template (To Be Defined), meaning: vector definition must specify its type. std::vector<int> v;

vector is a part C++ Standard Template Library, we don’t care how it is implemented, we can use its functions knowing only their description (i.e. interface). #include <vector> std::vector<int> v;

vector can be dynamically resized (in contrary to arrays ). v.push_back(num);

4

vector

#include <iostream>#include <vector>

int main(){std::vector<int> v;

//read numbers into a vector int num = 0; while (std::cin >> num ){

v.push_back(num); } for (std::vector<int>::size_type i = 0 ;

i < v.size() ; ++i ){ std::cout << v[i] << std::endl;

} return 0;}

5

When will this loop stop?

Non int value entered OR End-Of-File

value

Multi-dimensional vectors

There is no such thing!

What one can use is vector-of-vectors:std::vector<std::vector<int> > v(5);creates vector of 5 elements, each of them an empty vector of ints

To add a new (empty) row:v.push_back(vector<int>());

To add an int to a row:v[1].push_back(100);

To access an element (assumes it exists):v[i][j] = 23;

6

Note the space whitespace!

vector - iterator

A type that provides generic way for accessing sequencial container’s elements. Further information :

http://en.wikibooks.org/wiki/C++_Programming/Code/Design_Patterns#Iterator

Specific to vector’s type. std::vector<int>::iterator iter1;

Has a pointer like behavior (iterator != pointer). std::cout<<*iter; //print value if ( (*iter1)==(*iter2) ) ... //comparing values If ( iter1==iter2 )… // comparing addresses

Used by a number of functions. std::vector<int> v1; std::vector<int>::iterator iter = v1.begin();

7

vector - iterator

#include <vector>#include <iostream>

int ia[] = { 51, 23, 7, 88, 41 };

int main (){ // Initializing vector using ptr to begin and end std::vector<int> vec( ia, ia + sizeof(ia)/sizeof(int) ); // printing the vector

for (std::vector<int>::size_type i = 0 ; i < vec.size() ; i++ )

{ std::cout<< vec[i] << ", " ; } //another way to print

for ( std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++ )

{ std::cout<< (*iter) << ", " ;

}}

8

vector – const_iterator

std::vector<int>::const_iterator citer; const std::vector<int>::iterator iter;

const_iterator – doesn’t not allow to change the vector, but allows to iterate over a vector.std::vector<int>::const_iterator citer = vec.begin();

*citer = 5; //ERROR citer++; //OK

iterator defined as const – doesn’t allow to point to another location at the vector, but allows to change the value pointed.

const std::vector<int>::iterator iter = vec.begin(); *iter = 7; //OK iter++; //ERROR

9

Are NOT the same

*citer is const

iter is const

Agenda

vector and iterator

string

10

string A special type of container, designed to operate

with sequences of characters . Further information :

http://www.cplusplus.com/reference/string/string/

std::string stringOne( “my name” );

Unlike C-strings (char*) – string is a class which allows many built-in, powerful features.

Manages it’s own memory – easy and effective resizing.stringOne.append(“is John”);

stringOne.push_back(‘!’);

Easy iteration, search and comparison.string::iterator it = stringOne.begin();

11

string – examplesWhat will be the output?

#include <iostream> #include <string>

void main() { std::string stringOne("Hello World"); //init

std::string stringTwo(stringOne),stringThree; int i; stringTwo.append(" Again."); // equivalent to += std::cout << stringOne << std::endl; std::cout << stringTwo << std::endl; std::cout << stringOne + " " + stringTwo << etd::endl; std::cout << "Enter your name: ";

std::cin >> stringThree; std::cout << "Hello " << stringThree << std::endl;

}

12

string - examples (2)

std::string k,m,n,o,p; m = "David"; n = "and"; o = "Goliath"; k = "Solomon"; std::cout<< k << std::endl; std::cout<< m <<" "<< n <<" "<< o << std::endl; p = m + " " + n + " " + o; std::cout << p << std::endl; p.append(" meet at last!"); std::cout << p << std::endl;m = "Beware the ides of March"; n = m.substr(11,4); o = m.substr(19); p = m + n + o;std::cout << p << std::endl;std::cout << p.find(“hides”) << std::endl;13

Returns std::string::npo

sif substring isn’t found

Input parsing Suppose we want to get from the user the

following data: Year (into int) book title (into string) (if exists) book subtitle (into string)

“No subtitle” should be denoted by empty subtitle string

First attempt:

14

Input parsing

int year;std::string bookTitle, bookSubtitle; std::cout << "Enter year" << std::endl;std::cin >> year;std::cout << "Enter book title" << std::endl;std::cin >> bookTitle;std::cout << "Enter book subtitle" << std::endl;std::cin >> bookSubtitle; std::cout << "Year:" << year << std::endl;std::cout << "Title:" << bookTitle << std::endl;std::cout << "Subtitle:" << bookSubtitle << std::endl;

Look OK, right?

15

Input parsingEnter year1984Enter book titleThe good yearEnter book subtitleYear:1984Title:TheSubtitle:goodPress any key to continue . . .

What happened??? “>>” operator stops at whitespaces, and

can’t read empty strings! To read a string “as is”, we have to use the getline function

16

Input parsing – second try

int year;std::string bookTitle, bookSubtitle; std::cout << "Enter year" << std::endl;std::cin >> year;std::cout << "Enter book title" << std::endl;getline(std::cin, bookTitle);std::cout << "Enter book subtitle" << std::endl;getline(std::cin, bookSubtitle); std::cout << "Year:" << year << std::endl;std::cout << "Title:" << bookTitle << std::endl;std::cout << "Subtitle:" << bookSubtitle <<std::endl;

Looks OK, right?17

Input parsing – second try

Enter year1984Enter book titleEnter book subtitleThe good yearYear:1984Title:Subtitle:The good yearPress any key to continue . . .

Why did we skip title? ‘>>’ doesn’t remove trailing newlines! Arghhhh!!!!

18

Input parsing - solution Let’s go back to what we wanted in the first

place We wanted the user to input three lines - the

first for the year, the second for the title and the third for subtitle.

We know how to read a single line into a string – with getline

But how do we read an integer (year) from this string?

We apply ‘>>’ to it! To apply ‘>>’, we need to wrap the string

with a ‘istringstream’ (defined in <sstream>).

19

istringstream provides an interface to manipulate strings as input streams.

Using only cin object diagram: ?

Using also istringstream object (wrapper) diagram:

OK

std::istringstream

Input parsing - solution

20

std::cin std::string

std::cin std::string

Input parsing - solution

int year;std::string yearStr, bookTitle, bookSubtitle;

std::cout << "Enter year" << std::endl;getline(std::cin, yearStr);std::istringstream input(yearStr);input >> year;std::cout << "Enter book title" << std::endl;getline(std::cin, bookTitle);std::cout << "Enter book subtitle" << std::endl;getline(std::cin, bookSubtitle);

std::cout << "Year:" << year << std::endl;std::cout << "Title:" << bookTitle << std::endl;std::cout << "Subtitle:" << bookSubtitle << std::endl;

21

Input parsing - solution

Enter year1984Enter book titleThe good yearEnter book subtitle

Year:1984Title:The good yearSubtitle:Press any key to continue . . .

That’s what we wanted! What will happen if we put 2001.3 in year?

2001July? July2001?

22