59
C++ Tutorial II Harvard Applied Math 225 1 1 Developed by Nick Derr, Dan Fortunato, and Chris Rycroft.

C++ Tutorial II - iacs-courses.seas.harvard.eduiacs-courses.seas.harvard.edu/courses/am225/tutorial/cpp_tutorial2.pdf · C++ Tutorial II Harvard Applied Math 2251 1Developed by Nick

  • Upload
    ngodien

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

C++ Tutorial IIHarvard Applied Math 2251

1Developed by Nick Derr, Dan Fortunato, and Chris Rycroft.

Useful System Functions

Several useful functions are contained in built-in libraries such as<cstdio>, <cstdlib>, and <cstring>. These can be accessed by#include-ing the relevant library

Examples include memcpy, rand and exit

memcpy - efficiently copy a block of bytes from onelocation in memory to anotherUsage: void* memcpy(void *destination, void *source, size t num)

I Does not care where you point it!I faster than copying with equivalent for loopI size t represents the size in bytes of an object or typeI use sizeof operator to obtain the size in bytes of a type

s

d

num

memcpy - efficiently copy a block of bytes from onelocation in memory to anotherUsage: void* memcpy(void *destination, void *source, size t num)

#include <cstring> // allows use of memcpy#include <cstdio> // allows use of printf

int main() {double two_nums[2] = {2.3, 4.2};double three_nums[3] = {0, 0, 0};

// copy contents of two_nums into last// two entries of three_numsmemcpy(&three_nums[1],two_nums,2*sizeof(double));

// print contents of three_numsprintf("[%g %g %g]\n",three_nums[0],three_nums[1],

three_nums[2]);}

[0 2.3 4.2]

rand - pseudorandom number generator for integersUsage: int rand()

I rand is provided within the <cstdlib> library

I returns an integer between zero and RAND MAX (≥ 32, 767)

I uniform random integer on [0,m): rand() % mI random float on [0, 1]:

( (float) rand() ) / ( (float) MAX RAND )

I Not a good RNG! For random number generators that moreclosely approximate random behavior, see the <random>library or the GNU Scientific Library (GSL) set of RNGs.

exit - stop execution and report program statusUsage: void exit(int status)

I terminates process normally

I calling with status=0 indicates successI can cleanly stop when problem is detected

I file failed to openI user passed invalid input to program

#include <cstdlib> // allow use of exit,rand

int main() {// roll a dieint r = 1 + (rand() % 6);

// an odd roll corresponds to failureif (r%2 != 0) exit(-1);

// an even roll corresponds to successreturn 0;

}

Input/Output

I In the first tutorial, we saw how to print in two ways: C-style(puts, printf) and C++-style (std::cout <<)

I The C (<cstdio>) and C++ (<iostream>) I/O libraries arebased on input and output streams rather than the particulardevices receiving output or providing input

C++program

Input Stream

Output Stream

Input Source

(keyboard, file)

Output Sink

(console, file)

I Printing to console is just writing to special file stream!

Special I/O streams

I standard input: default source of data for applications,typically directed to the keyboardI C-style: stdinI C++-style: std::cin

I standard output: default destination of output forapplications, typically directed to the consoleI C-style: stdoutI C++-style: std::cout

I standard error: default destination of error messages andother diagnostic warnings, typically directed to the consoleI C-style: stderrI C++-style: std::cerrI Difference between output streams? If stdout is directed away

from console, frequently stderr will remain directed there

Special I/O streams

I standard input: default source of data for applications,typically directed to the keyboardI C-style: stdinI C++-style: std::cin

I standard output: default destination of output forapplications, typically directed to the consoleI C-style: stdoutI C++-style: std::cout

I standard error: default destination of error messages andother diagnostic warnings, typically directed to the consoleI C-style: stderrI C++-style: std::cerrI Difference between output streams? If stdout is directed away

from console, frequently stderr will remain directed there

Special I/O streams

I standard input: default source of data for applications,typically directed to the keyboardI C-style: stdinI C++-style: std::cin

I standard output: default destination of output forapplications, typically directed to the consoleI C-style: stdoutI C++-style: std::cout

I standard error: default destination of error messages andother diagnostic warnings, typically directed to the consoleI C-style: stderrI C++-style: std::cerrI Difference between output streams? If stdout is directed away

from console, frequently stderr will remain directed there

Printing vs Writing

I More generally, can write to streams representing files,networks, devices, etc.

I C-style: replace functions with more general versions

puts(const char* str)→ fputs(const char* str,FILE* stream)

printf(...)→ fprintf(FILE* stream,...)

I puts(...) ⇐⇒ fputs(...,stdout)I printf(...) ⇐⇒ fprintf(stdout,...).

I C++ style: just use particular I/O stream object in place ofstd::cin or std::cout

Opening I/O streams to files

I C-style: I/O streams represented by FILE* objectsI C++ style: I/O streams represented by std::istream and

std::ostream objectsI streams to files represented by subclasses: std::ofstream,

std::ifstream, and std::fstream

#include <cstdio> // C-style#include <iostream> // C++ style#include <fstream> // C++ style for files

int main() {

// C-style output stream for writing to a fileFILE *fh = fopen("output.txt","w");

// C++ style output stream for appending to a filestd::ofstream fout;fout.open("output2.txt",std::ofstream::app);

...

Opening I/O streams to files

I Streams to/from files must be opened and closed by the user

I Must specify why file is being opened with a mode argument

I C uses strings: "w" for write, "r" for read, "a" for append

I C++ uses class members: ios::out for read, ios::in forread, and ios::app for append. (Replace ios as below)

#include <cstdio> // C-style#include <iostream> // C++ style#include <fstream> // C++ style for files

int main() {

// C-style output stream for writing to a fileFILE *fh = fopen("output.txt","w");

// C++ style output stream for appending to a filestd::ofstream fout;fout.open("output2.txt",std::ofstream::app);

...

Opening I/O streams to files

I Safety first: what happens if file failed to open?I Check whether file is readable or writable before attempting

relevant operationsI C-style: check whether FILE* is NULL

...

// don’t proceed if file isn’t writableif (fh == NULL) {

// filestream arg goes at end of fputs callfputs("error: file failed to open",stderr);exit(-1);

}

// filestream is at front of fprintf callfprintf(fh,"I can write since file is open!\n");

...

Opening I/O streams to files

I Safety first: what happens if file failed to open?I Check whether file is readable or writable before attempting

relevant operationsI C++ style: check using <fstream> class functions

...

// don’t proceed if file isn’t writableif (!fout.is_open()) {

// send output to error streamstd::cerr << "error: file failed to open" << std::endl;exit(-1);

}

// only print if safefout << "I can append since file is open!" << std::endl;

...

Closing I/O streams to files

I Close files when finished reading or writing

I If writing, flushes output stream buffer

I Frees memory associated the open file

...// finished with C file. fh can now be reusedfclose(fh);

// finished with C++ file. fout can now be reusedfout.close();

}

output.txt

I can write since file is open!

output2.txt

<previous file contents>I can append since file is open!

Formatting output of text files

I One option for outputting data is to format text to thedesired precision and print in a systematic pattern

I C-style: pass format string of form "%m.n(.)"I width: m - number of spacesI precision: n - number of significant digits or decimal placesI type: (.) - type of formatting

I f - fixed-point (n - number of decimal places)I g - normal or exponential (n - number of significant digits)I d - signed integral numberI s - stringI c - characterI p - pointer address

I C++-style: pass functions or objects from <iomanip>(analogous to pieces of format string) to streamI width: std::setw(int width)I precision: std::setprecision(int precision)I type: e.g. std::fixed or std::scientific

Formatting output of text files

I One option for outputting data is to format text to thedesired precision and print in a systematic pattern

I C-style: pass format string of form "%m.n(.)"I width: m - number of spacesI precision: n - number of significant digits or decimal placesI type: (.) - type of formatting

I f - fixed-point (n - number of decimal places)I g - normal or exponential (n - number of significant digits)I d - signed integral numberI s - stringI c - characterI p - pointer address

I C++-style: pass functions or objects from <iomanip>(analogous to pieces of format string) to streamI width: std::setw(int width)I precision: std::setprecision(int precision)I type: e.g. std::fixed or std::scientific

Formatting output of text files

I One option for outputting data is to format text to thedesired precision and print in a systematic pattern

I C-style: pass format string of form "%m.n(.)"I width: m - number of spacesI precision: n - number of significant digits or decimal placesI type: (.) - type of formatting

I f - fixed-point (n - number of decimal places)I g - normal or exponential (n - number of significant digits)I d - signed integral numberI s - stringI c - characterI p - pointer address

I C++-style: pass functions or objects from <iomanip>(analogous to pieces of format string) to streamI width: std::setw(int width)I precision: std::setprecision(int precision)I type: e.g. std::fixed or std::scientific

Formatting output of text files

The two print statements below yield the same output

#include <cstdio> // C-style I/O#include <iostream> // C++ I/O#include <iomanip> // formatting functions

int main() {double pi = 3.1415926534;

// C formattingprintf("%.4f \n",pi);

// C++ formattingstd::cout << std::fixed << std::setprecision(4) << pi << std::endl;

}

3.14163.1416

Writing out binary files

I Another option when writing out data is to write a binary file,copying a block of memory directly to the file’s location

I signified with the mode argument when opening fileI C-style: "b"I C++ style: ios::bin

I For C-style I/O, the calling process is similar to memcpyI fwrite(void* p,size t size,size t num,FILE* stream)

#include <cstdio> // C-style I/O

int main() {float arr[5] = {.2, -.3, 1, 2, 321};

// append binary signifier to write signifierFILE *fb = fopen("dat","wb");fwrite(arr,sizeof(float),5,fb);fclose(fb);

}

Writing out binary files

I For C++ style I/O, the function used to write to the binaryfile is ofstream::write(char *p,size t num)

I Note that regardless of the data type in question, we need tocast its address as a char*.

#include <iostream> // C++ I/O#include <fstream> // file I/O

int main() {float arr[5] = {.2, -.3, 1, 2, 321};

// pass binary signifier while opening streamstd::ofstream fout;fout.open("dat",std::ofstream::bin);

// write out binary filefout.write((char*)arr, sizeof(float)*5);fout.close();

}

Exporting to outside applications

I Both kinds of exported data can be opened and manipulatedin other applicationsI Further processingI Data visualization

I Both Matlab and numpy have functions for importing dataI Text files

I np.loadtxt(filename,dtype=float,...)I Matlab: importdata(filename)

I Binary filesI np.fromfile(filename,dtype=float,count=-1,sep="")I Matlab: fread(fileID,sizeA,precision,...)

I For binary files, need to either pass arguments to specify datashape at time of read (Matlab) or reshape resulting array(numpy).

Reading in text files

I Reading text files is exactly analogous to writingI C-style I/O: fprintf is replaced by fscanf

I Returns number of arguments successfully filled

I C++ style I/O: fout << is replaced by fin >>I Returns bool with true for success

#include <cstdio> // C-style I/O#include <iostream> // C++ style I/O

int main() {// read in some integer entered at the command lineint ic, icpp;

// C-style - use a format string to// specify the data expectedfscanf(stdin,"%d",ic); // returns 1 if successful, 0 if not

// C++ stylestd::cin >> icpp; // returns true if successful, 0 if not

}

Reading in binary files

I C-style I/O: fwrite is replaced by freadI C++ style I/O: fout.write is replaced by fin.read

#include <cstdio> // C-style I/O#include <iostream> // C++ style I/O#include <fstream> // file I/O

int main() {// open up a binary file containing 12 doublesdouble data_c[12], data_cpp[12]; // put data here// open filesFILE *fh = fopen("dat","rb"); // C-stylestd::ifstream fin; // C++ stylefin.open("dat2",std::ifstream::bin);

// C-style readfread(data_c,sizeof(double),12,fh);// C++ style readfin.read((char*)data_cpp,12*sizeof(double));

// cleanupfclose(fh); fin.close();

}

Accessing command-line arguments

I Executables can be launched with information specified atrun-time in the form of command-line arguments

I Args are stored in two optional arguments of main:I argc - int with the number of argsI argv - **char containing each whitespace-separated argument

I The name of the executable is prepended to the start of argvI Arguments can be converted to correct data type using

C-style system functions or C++ style I/O streams

I C-style: from <cstdlib>, the functions int atoi(constchar* str) and float atof(const char* str) will returnthe integer or float corresponding to the provided string, orthe value 0 if the string is invalid

Accessing command-line arguments

I When looping through the arguments, remember that the first“argument” is just the executable name

I Assume the following is compiled to arg test and run with./arg test arg1 a two 3.

#include <cstdio> // C-style I/O

int main(int argc,char **argv) {for (int i=0; i<argc; i++) {

printf(" %s ",argv[i]);}printf("\n");

}

arg_test arg1 a_two 3

Accessing command-line arguments

Input validation is easier with the C++ method. In the case offailure, atoi and atof return 0. Here we read first arg as an int.

#include <cstdio> // C-style I/O#include <cstdlib> // atoi#include <iostream> // C++ I/O#include <sstream> // string stream objects

int main(int argc,char **argv) {int ac, acpp;

// if this is 0, is that because 0 provided or invalid input?ac = atoi(argv[1]);

// can explictly check conversion with streamstd::istringstream ss(argv[1]); // set up input streamif (!(ss >> acpp)) { // read in data

std::cerr << "Error: " << argv[1] <<" is not an integer" << std::endl;

exit(-1);}

}

Piping output at the command line

I another way to redirect the output (or input) of an executableis to pipe it to (or from) another process or file

I $ ./function > out: redirects stdout from the console tothe text file out. If out is already present, it is rewritten

I $ ./function >> out: redirects stdout from the console tothe text file out. If out is already present, the output isappended to its contents

I $ ./function < in: redirects stdin from the keyboard tothe text file in

I $ ./function | ./function2: pipes stdout fromfunction to stdin for function2

Redirecting stdout in this way will not redirect stderr! Errormessages will still be printed to the console.

Object-oriented programming (OOP)Overview

Historically, programming was viewed as a procedural task.

How do I define the logic in my program to do what Iwant?

OOP takes the view that what we really care about are theobjects we want to manipulate, rather than the logic required tomanipulate them.

How do I define the data in my program to reflect whatI’m trying to do?

Object-oriented programming (OOP)Overview

OOP is a paradigm based on modular coding. Objects containdata and actions to manipulate their data.

OOP allows you to

I ...think abstractly about the problem you are trying to solve.

I ...reason about your program clearly.

I ...maintain and debug your code easily.

I ...use existing codes from external libraries as a black box.

There are two types of objects in C++: structs and classes.

Structs

A struct is an object type for holding data.† You can access datainside the struct with the . operator.

struct Person {std::string name;int age;

};

Person p;p.name = "Dan";p.age = 26;

†Historically, structs were only meant for holding data, but they can alsocontain functions to manipulate the data, as we will see.

Classes

A class is an object type for holding and manipulating data.Classes contain two things:

I Members: The data held by the class

I Methods: The functions provided by the class to manipulatethe members

class Player {public:

void move();void jump();void shoot();int getScore();bool isDead();

private:int id, score, health;double x, y;

};

ClassesAccess control

Classes provide access control to their members and methods viathe keywords public, private, and protected.

I Public members are accessible by anyone.

I Private members are only accessible within the class definingthem.

I Protected members are accessible within the class definingthem and in classes that inherit from that class.

By default, all classes members and methods are private unlessexplicitly specified.

ClassesConstructors and destructors

Classes have some special functions that are called automaticallywhen your program runs.

The constructor is called whenever you declare a new instance ofthe class. It is used to initialize the data in the class.

I Named the same as the class.

I May take arguments.

I Has no return type.

The destructor is called when an instance of the class goes out ofscope or is deleted. It is used to clean up things like allocatedmemory.

I Named the same as the class with a ~ in front.

I Takes no arguments.

I Has no return type.

#include <string>

class Person {public:

Person(const std::string& name, int age) { // Constructorname_ = name;age_ = age;annualHealth_ = new int[age_];

}∼Person() { // Destructor

delete [] annualHealth_;}void setHealth(int age, int health) {

annualHealth_[age-1] = health;}

private:std::string name_;int age_;int* annualHealth_;

};

int main() {Person me("Dan", 26); // Constructor is called hereme.setHealth(26, 100);

} // Destructor is called here

#include <string>

class Person {public:

Person(const std::string& name, int age) : // Constructorname_(name), age_(age), annualHealth_(new int[age_])

{}∼Person() { // Destructor

delete [] annualHealth_;}void setHealth(int age, int health) {

annualHealth_[age-1] = health;}

private:std::string name_;int age_;int* annualHealth_;

};

int main() {Person me("Dan", 26); // Constructor is called hereme.setHealth(26, 100);

} // Destructor is called here

ClassesInheritance

One of the most useful concepts in OOP is inheritance: thecapability of a class to derive characteristics from another class.

I The base class (or super class) provides members andmethods.

I The derived class (or sub class) inherits members andmethods from a base class, on top of which it can add its own.

Animal

TigerLion Bear

class Animal {public:

Animal(int age, int weight, bool isCarnivore) :age_(age), weight_(weight), isCarnivore_(isCarnivore) {}

void eat() {// How does a generic Animal eat?

}void sleep() {

// How does a generic Animal sleep?}

protected:int age_, weight_;bool isCarnivore_;

};

class Lion : public Animal {public:

Lion(int age, int weight) : Animal(age, weight, true) {}void roar();void eat() {

// How do Lions eat?}

private:bool isAlpha_;

};

ClassesInheritance

To inherit from a class, use a : and then specify the class(es) youwant to inherit from (there can be multiple!) and the type ofinheritance. There are three types:

I public inheritance:

Base

public membersprotected membersprivate members

Derived

public membersprotected members

ClassesInheritance

To inherit from a class, use a : and then specify the class(es) youwant to inherit from (there can be multiple!) and the type ofinheritance. There are three types:

I protected inheritance:

Base

public membersprotected membersprivate members

Derived

protected members

ClassesInheritance

To inherit from a class, use a : and then specify the class(es) youwant to inherit from (there can be multiple!) and the type ofinheritance. There are three types:

I private inheritance:

Base

public membersprotected membersprivate members

Derived

private members

ClassesInheritance

To inherit from a class, use a : and then specify the class(es) youwant to inherit from (there can be multiple!) and the type ofinheritance. There are three types:

I private inheritance:

Base

public membersprotected membersprivate members

Derived

private members

To inherit from multiple classes, separate the base classes withcommas.

Classesvirtual functions

Suppose we want to write a function that works for any type ofbase class:

void func(const Animal& a) { a.eat(); }

We would like to be able to pass any derived class type and have itdo the right thing, but...

Animal a;Lion l;func(a); // Calls the generic Animal eat()func(l); // Calls the generic Animal eat()

Uh oh... Do we need to make a new func just for Lions?

No! We can use the keyword virtual.

Classesvirtual functions

Suppose we want to write a function that works for any type ofbase class:

void func(const Animal& a) { a.eat(); }

We would like to be able to pass any derived class type and have itdo the right thing, but...

Animal a;Lion l;func(a); // Calls the generic Animal eat()func(l); // Calls the generic Animal eat()

Uh oh... Do we need to make a new func just for Lions?

No! We can use the keyword virtual.

class Animal {public:

Animal(int age, int weight, bool isCarnivore) :age_(age), weight_(weight), isCarnivore_(isCarnivore) {}

virtual void eat() {// How does a generic Animal eat?

}virtual void sleep() {

// How does a generic Animal sleep?}

protected:int age_, weight_;bool isCarnivore_;

};

class Lion : public Animal {public:

Lion(int age, int weight) : Animal(age, weight, true) {}void roar();void eat() {

// How do Lions eat?}

private:bool isAlpha_;

};

Classesvirtual functions

Now our function does the right thing:

Animal a;Lion l;func(a); // Calls the generic Animal eat()func(l); // Calls Lion’s eat()

A base class determines what functionality a derived class willinherit, but it does not have to implement the functionality. Suchfunctions are called pure virtual functions.

The burden of implementation is left to the derived class.

Classesvirtual functions

Now our function does the right thing:

Animal a;Lion l;func(a); // Calls the generic Animal eat()func(l); // Calls Lion’s eat()

A base class determines what functionality a derived class willinherit, but it does not have to implement the functionality. Suchfunctions are called pure virtual functions.

The burden of implementation is left to the derived class.

Classesvirtual functions

class Shape {public:

virtual double area() = 0; // Pure virtual function};class Circle : public Shape {

public:double area() { return M_PI*r*r; }

private:double radius;

};class Rectangle : public Shape {

public:double area() { return width*height; }

private:double width, height;

};

ClassesAllocating classes

Just like other types, classes can be allocated on the stack or theheap. Depending on the size of your class, you may choose to doeither.

Person p("Dan", 26);Person* q = new Person("Dan", 26);delete q;

A pointer to a class must first be dereferenced (using *) before itsmembers can be accessed (using .). This operation is so commonthat there is a special operator for it: ->.

Person* q = new Person("Dan", 26);(*q).setHealth(26, 100);q->setHealth(26, 100); // Samedelete q;

Namespaces

All variables, objects, and functions have a namespace, whichdefines where their names live.

Think of namespaces as “full names.” If I’m the only Dan in aroom then using my first name is clear, but if there are other Danspresent then using my first name is not enough and specificitymust be added.

Namespaces precede names with a :: (e.g. std::string).Global variables live in the empty namespace (e.g. ::x).

Namespaces

#include <cstdio>

int x = 1;

namespace AM225 {int x = 2;class Example {

public:void run() {

int x = 4;printf("%d %d %d %d\n", x, Example::x, AM225::x, ::x);

}private:

int x = 3;};

}

int main() {AM225::Example ex;ex.run();

}

4 3 2 1

ClassesInterface vs. implementation

Separating the interface of a class (the way to use it) from itsimplementation (the way it works) is the key to OOP. To reflectthis separation, classes are often declared in a .hh/.h file andimplemented in a .cc/.cpp file.

When a part of your code wants to use the class, you simply#include the header file.

ClassesInterface vs. implementation

vec3.h

#ifndef VEC3_H#define VEC3_Hclass Vec3 {

public:double l2_norm();double x, y, z;

};#endif

vec3.cpp

#include <cmath>

Vec3::l2_norm() {return sqrt(x*x + y*y + z*z);

}

main.cpp

#include <cstdio>#include "vec3.h"

int main() {Vec3 v;v.x = 1.2; v.y = -3; v.z = 4.4;double norm = v.l2_norm();v.x /= norm; v.y /= norm; v.z /= norm;printf("||v|| was %g, but now is %g\n", norm, v.l2_norm());

}

Classes vs. structs

A struct is a class whose members and methods are all public.

#include <cstdio>#include <cmath>

class Vec3 {public:

double l2_norm() {return sqrt(x*x + y*y + z*z);

}double x, y, z;

};

int main() {Vec3 v;v.x = 1.2; v.y = -3; v.z = 4.4;double norm = v.l2_norm();v.x /= norm; v.y /= norm; v.z /= norm;printf("||v|| was %g, but now is %g\n", norm, v.l2_norm());

}

||v|| was 5.45894, but now is 1

Classes vs. structs

A struct is a class whose members and methods are all public.

#include <cstdio>#include <cmath>

struct Vec3 {double l2_norm() {

return sqrt(x*x + y*y + z*z);}double x, y, z;

};

int main() {Vec3 v;v.x = 1.2; v.y = -3; v.z = 4.4;double norm = v.l2_norm();v.x /= norm; v.y /= norm; v.z /= norm;printf("||v|| was %g, but now is %g\n", norm, v.l2_norm());

}

||v|| was 5.45894, but now is 1

The keyword thisEvery instance of a class has a notion of self via a special pointercalled this, which points to the instance of the class. All(non-static) member functions have access to this.

#include <cstdio>

class Coordinate {public:

Coordinate(double x = 0, double y = 0) : x_(x), y_(y) {}Coordinate& setX(double x) { x_ = x; return *this; }Coordinate& setY(double y) { y_ = y; return *this; }void print() { printf("(%g,%g)\n",x_,y_); }

private:double x_, y_;

};

int main() {Coordinate c(1,2);c.setX(-2.7).setY(9.2);c.print();

}

(-2.7,9.2)

The Standard Template Library (STL)

C++ provides many useful features in an external library called theSTL. You can access them by #include-ing various headers.

I Contiguous memoryI Heap-allocated: std::vector in <vector>I Stack-allocated: std::array in <array>

I SetI std::set in <set>I std::unordered set in <unordered set>

I Key-value storageI std::map in <map>I std::unordered map in <unordered map>

I Data structuresI std::stack in <stack>I std::queue in <queue>

I AlgorithmsI std::sort, std::fill, std::min/max, etc. in <algorithm>

#include <iostream>#include <vector>#include <array>#include <algorithm>

int main() {std::vector<double> v = {0.4, -5.6, 2};v.push_back(1.2);v.push_back(3.4);v.pop_back();v[2] = 10;std::vector<double>::iterator it = std::find(v.begin(), v.end(), 3.4);std::cout << (it!=v.end() ? "Found!" : "Not found.") << std::endl;

std::array<int,5> a = {7, 3, 5, -2, 0};a[1] = 1;std::sort(a.begin(), a.end());for (unsigned int i=0; i<a.size(); ++i) {

std::cout << a[i] << " ";}std::cout << std::endl;

}

Not found.-2 0 1 5 7