- 快召唤伙伴们来围观吧
- 微博 QQ QQ空间 贴吧
- 文档嵌入链接
- 复制
- 微信扫一扫分享
- 已成功复制到剪贴板
Programming in C++
展开查看详情
1 .Mitglied der Helmholtz-Gemeinschaft Programming in C++ Introduction to the language standard C++14 ( and a preview of C++17 ) 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre Chapter 1 Introduction 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 2 330
2 . C++ ∗ Express ideas in code Specify actions to be Direct mappings of built executed by the machine in operations and types to Concepts to use when hardware thinking about what can Affordable and flexible be done abstraction mechanisms C++ is a language for developing and using elegant and efficient abstractions * Chapter 1, The C++ Programming Language, 4th Edition, Bjarne Stroustrup 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 3 330 C++ Goals General purpose: no specialization to specific usage areas No over simplification that precludes a direct expert level use of hardware resources Leave no room for a lower level language What you don’t use, you don’t pay for 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 4 330
3 . Goals Express ideas directly in code Express independent ideas independently in code Represent relationships among ideas directly in code Combine ideas expressed in code freely Express simple ideas with simple code 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 5 330 Programming Styles A programming Programming styles in C++ solution should be... Procedural programming Small Data abstraction Fast Object oriented programming Correct Generic programming Readable Functional programming Maintainable C++ is not restricted to any specific programming style. Choose any combination of the above that fits best with the problem you are trying to solve. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 6 330
4 . C++ in 2017 Current standard, C++14. list<pair<string,size_t>> F; Follows C++11, precedes for (auto entry : freq) F.push_back(entry); C++17, to be finalised later F.sort([](auto i, auto j) { this year. return i.second < j.second; }); Easier, cleaner and more // with C++17 ... for (auto planet : solar_system) { efficient language auto [Decln, RA] = planet.calc_coordinates(ut); // ... } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 7 330 Compiler support for C++11/C++14 (May 2017) LLVM/clang++ : Complete (Version 3.4 and above). Useful error messages. Fast compilation. Generated binaries competitive with others. Own STL : libc++. GCC/g++ : Complete (Version 5.0 and above). Mature code base. Own STL : libstdc++. In GCC 6.1.0, C++14 became the default language standard, and using any older standard requires --std=c++98 or --std=c++11 options. Intel Compiler : Practically complete (Version 2017.1). Great optimizer. Uses system STL. Not free. IBM XLC Compiler : Usable with version 14.1. System/external STL. Not free. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 8 330
5 . Course plan In this course you will ... study illustrative code and do programming exercises learn C++ according to the current language standard Essential C++ concepts Classes and class hierarchies Templates and generic programming learn to use the C++ standard library STL containers and algorithms Smart pointers, time library, random numbers, multi-threading ... learn to make graphical user interfaces for your C++ programs using Qt Quick 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 9 330 Resources Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14, Scott Meyers, ISBN 978-1491903995 The C++ Programming Language(Fourth Edition), Bjarne Stroustrup, ISBN 978-0321563842 The C++ Standard Library: A Tutorial and Reference, Nicolai M. Josuttis, ISBN 978-0-321-62321-8 C++11: Der Leitfaden für Programmierer zum neuen Standard, Rainer Grimm, ISBN 978-3-8273-3088-8 Structured Parallel Programming, Michael McCool, Arch D. Robinson, James Reinders, ISBN 978-0-12-415993-8 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 10 330
6 . Online Resources http://www.cplusplus.com/reference/ http://en.cppreference.com/ http://www.qt.io http://www.threadingbuildingblocks.org https://github.com/isocpp/CppCoreGuidelines git clone https://github.com/isocpp/CppCoreGuidelines.git 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 11 330 Elementary Constructs 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 12 330
7 . Getting started The first step: Hello World! Set up environment for using the a // Hello World! #include <iostream> recent version of g++. For example, int main() using environment modules: { std::cout<<"Hello, world!\n"; module load gcc/7.1.0 } Find your favourite text editor and type in the simple “hello world“ program in this slide Compile and run the program using the following commands : g++ helloworld.cc -o hello ./hello 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 13 330 Getting started Useful aliases We will use thin wrappers G and A (in $course_home/bin) for g++ and clang++, which fill in frequently used options. They are inserted into your PATH when you type module load course G is (roughly) a shorthand for g++ --std=c++14 -pedantic $* A is (roughly) a shorthand for clang++ -std=c++14 -pedantic -stdlib=libc++ $* Whichever compiler you choose to use, load the corresponding module : module load gcc/7.1.0 or module load gcc/6.3.0 or module load llvm/4.0.0 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 14 330
8 . Getting started Comments on the hello world program #include <header> tells the // Hello World #include <iostream> preprocessor to include the contents int main() { of header in the current std::cout<<"Hello, world!\n"; } "translation unit" #include "somefile" searches Comments in C++ for a file called somefile and start with // and run imports its contents to the end of the line The search for headers is performed Think of std::cout in an implementation defined way. as a sink which prints what you throw at it on the screen 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 15 330 Getting started Comments on the hello world program All C++ programs must contain a unique main() function All executable code is contained either in main(), or in functions invoked directly or indirectly from main() The return value for main() is canonically an integer. A value 0 means successful completion, any other value means errors. UNIX based operating systems make use of this. In a C++ main function, the return 0; at the end of main() can be omitted. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 16 330
9 . Getting started Command line arguments Main can be declared as int main // Hello xyz #include <iostream> (int argc, char *argv[]) to int main(int argc, char *argv[]) { accept parameters from the std::cout<<"Hello, "; if (argc > 1) command line std::cout <<argv[1]<< "!\n"; else The entire command line is broken } std::cout<<"world!\n"; into a sequence of character strings G hello_xyz.cc (by unquoted and unescaped white a.out bird space) and passed as the array argv The name of the program is the first string in this list, argv[0]. Therefore argc is never 0. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 17 330 The compilation process 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 18 330
10 . The compilation process Exercise 1.1: By passing the additional compiler option -v to g++, recompile the hello world program and observe the logs from different stages of the compilation process. Where does the g++ search for headers ? Where does clang++ look for headers ? Try clang++ -v hello.cc and clang++ -stdlib=libc++ -v hello.cc, and observe the differences. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 19 330 Code legibility double foo(double x, int i) { Code indentation double y=1; if (i>0) { for (int j=0;j<i;++j) { Human brains are not y *= x; } made for searching { and } else if (i<0) { for (int j=0;j>i;--j) { } in dense text y /= x; } return y; } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 20 330
11 . Style double foo(double x, int i) { Code indentation double y=1; if (i>0) { for (int j=0;j<i;++j) { Indenting code clarifies y *= x; } the logic } else if (i<0) { for (int j=0;j>i;--j) { y /= x; Misplaced brackets, } } braces etc. are easier to } return y; detect 4-5 levels of nesting is sometimes unavoidable Recommendation: indent with 2-4 spaces and be consistent! 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 21 330 Style double foo(double x, int i) { Code indentation double y=1; if (i>0) { for (int j=0;j<i;++j) { Set up your editor to y *= x; } indent automatically! } else if (i<0) { for (int j=0;j>i;--j) { y /= x; Use a consistent } } convention for braces ({ } return y; and }). These are for the human reader (most often, yourself!). Be nice to yourself, and write code that is easy on the eye! 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 22 330
12 . Types, variables and declarations long n_particles{1000}; // 64 bits interpreted with rules for integers const double G{6.67408e-11}; // 64 bits interpreted as a floating point number char user_choice=’y’; bool received_ngb_updates=false; A "type" defines the possible values and operations for an object An "object" is some memory holding a value of a certain type A "value" is bits interpreted according to a certain type A "variable" is a named object Every expression has a "type" A "declaration" is a statement introducing a name into the program C++ is a statically typed language 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 23 330 Types, variables and declarations Types like char, int, float, double are known as fundamental types Fundamental types can be inter-converted when possible Arithmetic operations +, −, ∗, /, as well as comparisons <, >, <=, >=, ==, ! = are defined for the fundamental types, and mapped in an obvious way to low level instructions As in many languages, = is assignment where as == is equality comparison Note how variables are "initialized" to sensible values when they are declared 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 24 330
13 . Initialization Both int i=23 and int i{23} are valid initializations The newer curly bracket form should be preferred, as it does not allow "narrowing" initializations: int i{2.3}; //Compiler error The curly bracket form can also be used to initialise C++ collections: std::list<double> masses{0.511, 938.28, 939.57}; std::vector<int> scores{667,1}; // Vector of two elements, 667 and 1 std::vector<int> lows(250,0); // vector of 250 zeros The old initialisation notation with () is needed in some cases Variables can be declared anywhere in the program. So, avoid declaring a variable until you have something meaningful to store in it 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 25 330 The C++11 uniform initialisation syntax int I{20}; Variables can be initialised at // define integer I and set it to 20 string nat{"Germany"}; declaration with a suitable // define and initialise a string double a[4]{1.,22.1,19.3,14.1}; value enclosed in {} // arrays have the same syntax tuple<int,int,double> x{0,0,3.14}; // So do tuples Pre-C++11, only the = and list<string> L{"abc","def","ghi"}; // and lists, vectors etc. () notations (also double m=0.5; // Initialising with ’=’ // is ok for simple variables, but ... demonstrated in the left int k=5.3; // Allowed, although the panel) were available. // integer k stores 5, and not 5.3 int j{5.3}; // Helpful compiler error. Initialising non trivial int i{}; // i=0 vector<int> u{4,0};// u={4, 0} collections was not allowed. vector<int> v(4,0);// v={0, 0, 0, 0} Recommendation: Use {} initialisation syntax as your default. A few exceptional situations requiring the () or = syntax can be seen in the left panel. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 26 330
14 . The keywords auto and decltype int sqr(int x) If a variable is initialised { return x*x; when it is declared, in such a } int main() way that its type is { char oldchoice{’u’},choice{’y’}; unambiguous, the keyword size_t i=20’000’000;//grouping in C++14 double electron_mass{0.511}; auto can be used to declare int mes[6]{33,22,34,0,89,3}; bool flag{true}; its type decltype(i) j{9}; auto positron_mass = electron_mass; The keyword decltype can auto f = sqr; // Without "auto", f can // be declared like this: be used to say "same type as //int (*f)(int)=&sqr; std::cout << f(j) << ’\n’; that one" auto muon_mass{105.6583745}; // In C++17, if somefunc() returns // tuple<string, int, double> In C++17, several variables auto [name, nspinstates, lifetime] = somefunc(serno); can be declared and } initialised together from a suitable tuple, as shown 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 27 330 Scope of variable names double find_root() Variable declarations are { if (not initialized()) init_arrays(); allowed throughout the code for (int i=0;i<N;++i) { // loop counter i defined only A scope is : // for this "for" loop. } A block of code, bounded by double newval=0; // This is ok. for (int i=0;i<N;++i) { { and } // The counter i here is a // different entity A loop or a function body if (newval < 5) { string fl{"small.dat"}; (C++17) Both if and // do something else parts of an if } newval=...; statement cout << fl << ’\n’; // Error! } Variables defined in a scope int fl=42; // ok // C++17 exist from the point of if (auto fl=filename; val < 5) { // fl is available here declaration till the end of the } else { // fl is also available here scope. After that, the name } } may be reused. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 28 330
15 . Example 1.1: The programs examples/vardecl.cc, examples/vardecl2.cc and vardecl_in_if.cc demonstrate variable declarations in C++. Use g++ program.cc -o program to compile. For the last one, you will need the option -std=c++1z. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 29 330 C++ namespaces // Somewhere in the header iostream A namespace is a named namespace std { ostream cout; context in which variables, } functions etc. are defined. // In your program ... #include <iostream> The symbol :: is called the int main() { scope resolution operator. for (int cout=0;cout<5;++cout) std::cout<<"Counter="<<cout<<’\n’; using namespace blah // Above, plain cout is an integer, imports all names declared // but std::cout is an output stream // The syntax to refer to a name inside the // // defined inside a namespace is: namespace_name::identifier_name namespace blah to the } current scope. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 30 330
16 . C++ namespaces // examples/namespaces.cc No name clash due to the #include <iostream> using namespace std; same name in different namespace UnitedKingdom { namespaces string London{"Big city"}; } void load_slang() {...} Functions defined inside namespace UnitedStates { namespaces need to be string London{"Small town in Kentucky"}; void load_slang() {...} accessed using the same } scope rules as variables int main() { using namespace UnitedKingdom; cout<<London<<’\n’; cout<<UnitedStates::London<<’\n’; } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 31 330 C++ namespaces // examples/multdef/somehdr.hh Variables declared outside extern int D; bool f(int); any function are global bool g(int); // examples/multdef/file1.cc variables and live for the #include "somehdr.hh" bool f(int x) entire duration of the { return x>D; program } // examples/multdef/file2.cc #include "somehdr.hh" For non-constant variables bool g(int x) declared in a namespace { return x*x<=D; (global or not), the extern } // examples/multdef/main.cc keyword can be used to #include "somehdr.hh" int D=56; avoid multiple definitions int main() { if (f(23) or g(33)) return 1; return 0; } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 32 330
17 . Example 1.2: The files in the directory examples/multdef illustrate the need and use of the extern keyword. The global variable D is used in functions f(int) and g(int), defined in file1.cc and file2.cc. It is only given a value in main.cc, where it is defined without the extern keyword. To compile, you need to do the following steps: G -c file1.cc G -c file2.cc G -c main.cc G file1.o file2.o main.o -o multdef Check what happens if you remove the extern in the header. In C++17, you can also declare D to be ”inline“, and assign a value in the header itself. There is also need to define it explicitly in any source file. Check this! 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 33 330 unnamed namespaces // examples/unnamednsp/somehdr.hh Global variables such as D bool f(int); bool g(int); in file1.cc and // examples/unnamednsp/file1.cc // namespace { file2.cc will clash during int D=42; // } linking bool f(int x) { return x>D; They can be enclosed in } // examples/unnamednsp/file2.cc anonymous namespaces as // namespace {} shown int D=23; // } bool g(int x) The unnamed namespace is { return x*x<=D; a uniquely named } // examples/unnamednsp/main.cc namespace with internal int main() { linkage 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 34 330
18 . Unnamed namespaces Example 1.3: The directory examples/unnamednsp contains the same files as examples/multdef, with unnamed namespaces enclosing the variables D in files file(1|2).cc. Comment/uncomment the namespace boundaries and try to build. With the unnamed namespaces in place, the variables in the two files are independent of each other. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 35 330 Inline namespaces and versioning namespace myl { Identifiers declared inside an inline namespace V200 { double solve(); inline namespace are } namespace V150 { automatically exported to the double solve(); } surrounding namespace, as if namespace V100 { double solve(); there was an implicit } } using namespace ... void elsewhere(){ myl::solve(); //myl::V200::solve() Useful tool for vending a myl::V150::solve(); //as it says. } library where you must support multiple versions of something 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 36 330
19 . C++ namespaces: Final comments //examples/namespaces2.cc namespaces can be nested. #include <iostream> namespace UnitedKingdom In C++17, direct nested { std::string London{"Big city"}; declarations are allowed. } namespace UnitedStates { Long namespace names can namespace KY { std::string London{" in Kentucky"}; be given aliases } namespace OH { Tip1: Don’t indiscriminately std::string London{" in Ohio"}; } put using namespace ... } // With C++17 ... tags, especially in headers. namespace mylibrary::onefeature { double solve(int i); Tip2: The purpose of } int main() namespaces is to avoid { namespace USOH=UnitedStates::OH; name clashes. Not std::cout<<"London is" <<USOH::London<<’\n’; taxonomy! } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 37 330 Preprocessor directives Example 1.4: The program examples/bits_in_int.cc counts the number of 1 bits in the binary representation of the numbers you enter. Compile and run to check. Then use the C preprocessor cpp to process the file. The output is what the compiler receives. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 38 330
20 . Preprocessor directives #include <iostream> Processed before the unsigned char n_on_bits(int b) { compiler checks language #define B2(n) n, n+1, n+1, n+2 #define B4(n) B2(n), B2(n+1), \ syntax B2(n+1), B2(n+2) #define B6(n) B4(n), B4(n+1), \ #define pat sub B4(n+1), B4(n+2) const unsigned char tbl[256] { B6(0), B6(1), B6(1), B6(2) }; substitutes any occurrence of #undef B6 pat in the source with sub return tbl[b & 0xff] + tbl[(b>> 8) & 0xff] + Definitions valid until tbl[(b>>16) & 0xff] + tbl[(b>>24) & 0xff]; #undef. Scoping rules of the } int main() language do not apply. { #ifdef B6 Uses: reduce code text, #error B6 should not be defined! #endif tailored compiler errors, hints ... to the compilers (e.g. #pragma) 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 39 330 Compile time assertions double advance(unsigned long L) { static_assert(sizeof(L)>=8,"long type must be at least 8 bytes)"); //Bit manipulation assuming "long" is at least 8 bytes } Prints the second argument as an error message if the first argument evaluates to false. Express assumptions clearly, so that the compiler notifies you when they are violated In C++17, you can leave out the message parameter 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 40 330
21 . The type bool bool debugging=false; Possible values true or ... if (debugging) { false std::cout<<"additional messages.\n"; } Can be converted back and forth from integer types 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 41 330 C-style enumerations enum color { red, green, blue }; A type whose instances can using rgbtype = array<float, 3>; rgbtype adjust(rgbtype rgb) take a few different values { float factors[3]{0.8,1.0,0.93}; (e.g., directions on the rgb[red] *= factors[red]; rgb[green] *= factors[green]; screen, colours, supported rgb[blue] *= factors[blue]; return rgb; output modes ...) } Less error prone than using integers with ad hoc rules like, ”1 means red, 2 means green ...“ Internally represented as (and convertible to) an integer All type information is lost upon conversion into an integer 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 42 330
22 . Scoped enumerations Defined with enum class enum class color { red, green, blue }; enum class traffic_light { Must always be fully qualified }; red,yellow,green when used: bool should_brake(traffic_light c); traffic_light::red etc. if (should_brake(blue)) apply_brakes(); //Syntax error! if (state==traffic_light::yellow) ...; No automatic conversion to int. Possible to use the same name, e.g., green, in two different scoped enums. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 43 330 Pointers and references int i{5}; A pointer is an integral type int * iptr{&i}; // iptr points at i i+=1; to store the memory address std::cout << *iptr ; // 6 (*iptr)=0; of objects std::cout << i ; // 0 int & iref{i}; // iref "refers" to i iref=4; If iptr is a pointer, *iptr is std::cout << i ; // 4 the object it is pointing at For a variable X, its memory address can be obtained using &X A reference is a restricted pointer which must always point at the same object When in use, a reference appears as if it were a regular variable 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 44 330
23 . C++ standard library strings #include <string> Character strings ... std::string fullname; std::string name{"Albert"}; String of characters std::string surname{"Einstein"}; //Concatenation and assignment Knows its size (see example) fullname=name+" "+surname; Allocates and frees memory //Comparison if (name=="Godzilla") run(); as needed std::cout<<fullname<<’\n’; No need to worry about \0 for (size_t i=0;i<fullname.size();++i) { if (fullname[i]>’j’) blah+=fullname[i]; Can contain \0 in the middle } Simple syntax for assignment (=), concatenation(+), Don’t use C style strings! comparison (<,==,>) 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 45 330 C++ strings #include <ctype.h> #include <iostream> #include <stdio.h> #include <string> #include <string.h> int main() #include <stdlib.h> { int main() std::string name, bkpname; { std::cout << "What is your name ? "; char name[100], *bkpname; std::getline(std::cin,name); int nmsize,i; if (not name.empty()) { printf("What is your name ? "); bkpname = name; if ( fgets(name,100,stdin) ) { for (int i=0;i<name.size();++i) { nmsize = strlen(name); name[i]=toupper(name[i]); bkpname = (char *) malloc((nmsize+1)* } sizeof(char)); std::cout<<bkpname<<" <--> " bkpname = strdup(name); <<name<<"\n"; for (i=0;i<nmsize;++i) { } name[i]=toupper(name[i]); } } printf("%s <--> %s\n",bkpname,name); } if (bkpname) free(bkpname); Cleaner, easier to maintain return 0; } code using C++ strings. Did you notice the memory leak in the C code ? 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 46 330
24 . Raw string literals // Instead of ... string message{"The tag \"\\maketitle\" is unexpected here."}; // You can write ... string message{R"(The tag "\maketitle" is unexpected here.)"}; Can contain line breaks, ’\’ characters without escaping them Very useful with regular expressions Starts with R"( and ends with )" More general form R"delim( text )delim" Example 1.5: The file examples/rawstring.cc illustrates raw strings in use. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 47 330 Exercise 1.2: The file exercises/raw1.cc has a small program printing a message about using the continuation character ’\’ at the end of the line to continue the input. Modify using raw string literals. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 48 330
25 . Converting to and from strings std::cout << "integer : "<<std::to_string(i) << ’\n’; tot+=std::stod(line); // String-to-double The standard library string class provides functions to inter-convert with variables of type int, double Akin to atoi,strtod and using sprintf Example 1.6: Test example usage of string↔number conversions in examples/to_string.cc and examples/stoX.cc 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 49 330 Arrays double A[10]; // C-style array Fixed length C-style arrays int sz; std::cin >> sz; exist, but do not know their int M[sz]; // Not allowed! // Since C++11 ... own size #include <array> ... std::array<double,10> A; // On stack Variable length arrays of C99 // Like the C-style array, but obeys // C++ standard library conventions. are illegal in C++, although for (size_t i=0;i<A.size();++i) { P*=A[i]; tolerated with warnings in } many compilers std::vector<double> B(sz,3.0); std::array<type,size> is a compile-time fixed length array obeying STL conventions std::vector<type> is a dynamically allocated resizeable array type 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 50 330
26 . Branches/Selections if (condition) { The if and switch // code } else if (another condition) { constructs can be used to // code } else { select between different //code } alternatives at execution switch (enumarable) { case 1: time. // code break; case 2: Conditional assignments are // code frequently written with the break; default: ternary operator as shown // code }; x = N>10 ? 1.0 : 0.0; 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 51 330 Loops for (initialisation;condition;increment){ Execute a block of code // Loop body } repeatedly for (int i=0;i<N;++i) s+=a[i]; while (condition) {} while (T>t0) {} Loop counter for the for do {} while (condition); do { loop can and should usually } while (ch==’y’); for (variable : collection) {} be declared in the loop head for (int i : {1,2,3}) f(i); for (int i=0;i<N;++i) { The break keyword in a loop if (a[i]<cutoff) s+=a[i]; else break; immediately stops the loop } for (std::string s : names) { and jumps to the code if (s.size()>10) { longnames.push_back(s); following it continue; } The continue keyword skips // process other names } all remaining statements in the current iteration, and continues in the loop 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 52 330
27 . Exercise 1.3: What is the largest number in the Fibonacci sequence which can be represented as a 64 bit integer ? How many numbers of the sequence can be represented in 64 bits or less ? Write a C++ program to find out. Use only concepts presented so far. Exercise 1.4: Finish the program exercises/gcd.cc so that it computes and prints the greatest common divisor of two integers. The following algorithm (attributed to Euclid!) achieves it : 1 Input numbers : smaller , larger 2 remainder = larger mod smaller 3 larger = smaller 4 smaller = remainder 5 if smaller is not 0, go back to 2. 6 larger is the answer you are looking for 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 53 330 Range based for loops // Instead of ... //for (size_t i=0;i<fullname.size();++i) { // if (fullname[i]>’j’) blah+=fullname[i]; //} // you could write ... for (auto c : fullname) if (c>’j’) blah+=c; // Loop over a linked list ... std::list<double> L{0.5,0.633,0.389,0.34,0.01}; for (auto d : L ) { std::cout << d << ’\n’; } Anything that has a begin and an end Iteration over elements of a collection Use on strings, arrays, STL lists, maps ... 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 54 330
28 . Range based for loops // Loop over a small list of names ... for (auto day : { "Monday", "Tuesday", "Wednesday","Thursday","Friday"}) { std::cout << day << ’\n’; } // or a list of non contiguous integers ... for (auto i : { 1,1,2,3,5,8,13,21 }) { std::cout << Recs[i] << ’\n’; } Anything that has a begin and an end collections which provide a begin() and end() functions ... or which work well with global begin() and end() functions 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 55 330 Example 1.7: You will find two tiny example programs examples/loop.cc and examples/loop2.cc to demonstrate the range based for loops. Modify the code to write out an array of strings. 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 56 330
29 . Functions return_type function_name(parameters) All executable code is in { // function body functions } double sin(double x) { Logically connected reusable // Somehow calculate sin of x return answer; blocks of code } int main() A function must be called { constexpr double pi{3.141592653589793}; with values called arguments. for (int i=0;i<100;++i) { std::cout << i*pi/100 The type of the arguments << sin(i*pi/100) <<"\n"; } must match or be implicitly std::cout << sin("pi") <<"\n"; //Error! } convertible to the corresponding type in the function parameter list 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 57 330 Functions: Syntax // A function prototype A function prototype bool pythag(int i, int j, int k); // and a function definition introduces a name as a int hola(int i, int j) { function, its return type as int ans{0}; if (pythag(i,j,23)) { well as its parameters // A prototype or definition must be // visible in the translation unit // at the point of usage Functions can live freely ans=42; } C++11 introduced an return ans; } alternative syntax with the // Definition of pythag bool pythag(int i, int j, int k) return type coming after the { // code parameters (last example in } // Trailing return type (since C++11) the left panel) auto f(double x, double y)->double { // function body } 29 May – 01 June 2017 Sandipan Mohanty | Jülich Supercomputing Centre 58 330