1 / 54

Mastering Data Structures in C++: Practical Guidelines & Programming Exercises

Dive into the fundamentals of data structures in C++ with this comprehensive course. Learn essential concepts with practical examples, programming exercises, and recommended books. Uncover coding style tips, naming conventions, idioms, and debugging techniques to enhance your skills. Explore object-oriented design, generic programming, and template usage in C++. Ensure code clarity, readability, and maintainability by following best practices. Elevate your programming proficiency and tackle complex algorithms with confidence.

geva
Download Presentation

Mastering Data Structures in C++: Practical Guidelines & Programming Exercises

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Welcome to Data Structures in C++

  2. Course Staff • Teacher : • Ofir Pele • TA: • Teachers of other groups: • Roman Yavich

  3. Communications • WWW: moodle • Forums: • Q & A – ask the staff about material. • Exercises forums.

  4. Course • ~4 programming exercises • Frontal exam

  5. Books & Websites • Books: • A list here: http://www.cprogramming.com/books.html • Recommended for the more advanced stuff: • Scott Meyers “Effective” books (STL, C++). • C++ FAQ – Explaining the complicated stuff, corners etc. • C++ FQA – A bit lot more cynical & pragmatic view of the above

  6. Program style

  7. Program style • Take the time for it. Very important. If not followed your code will be “write only”. • Common sense • Read “real” coding guidelines document – will give you insight how important it is. e.g. good one from Microsoft or one from Google. • Principles: • Readability • Common Sense • Clarity • Right focus

  8. What’s in a name • Example #define ONE 1 #define TEN 10 #define TWENTY 20 • More reasonable #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20

  9. What’s in a name • Use descriptive names for global variables • intnpending = 0; // current length of input queue • Naming conventions vary (style) • numPending • num_pending • NumberOfPendingEvents • Be consistent, with yourself and peers.

  10. What’s in a name • Consider (wording) intnoOfItemsInQ; intfrontOfTheQueue; intqueueCapacity; … • The word “queue” appears in 3 different ways • Be consistent, with yourself and peers.

  11. What’s in a name • Compare for( theElementIndex = 0; theElementIndex < numberOfElements; theElementIndex++ ) elementArray[theElementIndex] = theElementIndex; and for( i = 0; i < nelems; i++ ) elem[i] = i; Use short names for locals

  12. What’s in a name Use active name for functions now = getDate() Compare if( checkdigit(c) ) … to if( isdigit(c) ) … Accurate active names makes bugs apparent

  13. Indentation Use indentation to show structure Compare for(n++; n <100; field[n++] = 0); c = 0; return ‘\n’; To for( n++; n <100; n++) { field[n] = 0; } c = 0; return ‘\n’;

  14. Expressions Use parenthesesto resolve ambiguity Compare • leap_year = y % 4 == 0 && y %100 != 0 || y % 400 == 0; to • leap_year = ((y % 4 == 0) && (y %100 != 0)) || (y % 400 == 0);

  15. Statements Use braces to resolve ambiguity Compare • if( i < 100 ) x = i; i++; To • if( i < 100 ) {   x = i; } i++;

  16. Idioms Do not try to make code “interesting”! • i = 0; while( i <= n-1 ) { • array[i++] = 1; • }for( i = 0; i < n; ) { • array[i++] = 1; • } • for( i = n; --i >= 0; ) { • array[i] = 1; • }for( i = 0; i < n; i++ ) { • array[i] = 1; • } This is the common “idiom” that any programmer will recognize

  17. Idioms Use “else if” for multiway decisions if ( cond1 ) { statement1 } elseif ( cond2 ) { statement2 } … else if ( condn ) { statementn } else { default-statement }

  18. Idioms Compare: if( x > 0 ) if( y > 0 ) if( x+y < 100 ) {    ... } elseprintf(Too large!\n" ); elseprintf("y too small!\n"); elseprintf("x too small!\n"); if( x <= 0 ) { printf("x too small!\n"); } elseif( y <= 0 ) { printf("y too small!\n"); }elseif( x+y >= 100 ) {printf("Sum too large!\n" ); }else{   ... }

  19. Comments • Don’t write the obvious • // return SUCCESS return SUCCESS; // Initialize total to number_receivedtotal = number_received; • Test: • Does comment add something that is not evident from the code? • Note: “//” Comments are Not Strict ANSI C, but supported by all modern compilers, and clearer in many cases

  20. Comments • Don’t comment bad code – rewrite it! • … • // If result = 0 a match was found so return // true; otherwise return false; return !result; • Instead • … • returnmatchfound;

  21. Style recap • Descriptive names • Clarity in expressions • Straightforward flow • Readability of code & comments • Consistent conventions & idioms

  22. Why Bother? • Good style: • Easy to understand code • Smaller & polished • Makes errors apparent • Sloppy style bad code • Hard to read • Broken flow • Harder to find errors & correct them

  23. Note - style in slides: • In the slides we try to follow the style we dictate. • Butdue to space restriction we sometimes bend the rules. • Don’t follow everything you see in the slides.

  24. Debugging

  25. Debugging 101 • “Define” the bug --- reproduce it • Use debugger and printouts (and other tools e.g. valgrind) • Don’t panic --- think! • Divide & Conquer

  26. From C to C++

  27. Why C++ is much more fun than C (C++ FAQ)? Classes & methods - OO design Generic programming - Templates allow for code reuse Stricter type system (e.g. function args) Some run-time checks & memory control A common and mature language that gives you high level and low level control Have fun 

  28. Why C++ is much more fun than c (C+ FQA)? Tons of corner cases Duplicate features Cryptic syntax Undecidable syntax (uncompilableprogarms!) No two compilers agree on it Probably one of the hardest computer languages to master. Have fun 

  29. History tr1: library additions ('05) auto, lambdas, threading,… Practically current c++ Minor changes Major compilers: Latest versions are starting to implement features from c++11 (prev. c++0x) approved draft

  30. Course Objectives • Learn the language • Practice of programming data structures • Design • Testing & Debugging • Efficiency & Portability • Modularity

  31. Course structure

  32. First Program in C++ • // This line includes the standard // I/O library file (similar to “copy here this file”) #include<iostream>int main() {    std::cout << "Hello class!\n"; return0; }

  33. Compiling & Running… • Visual Studio… • In Linux: • > g++ –Wall hello.cpp –o hello • > hello • Hello class! • >

  34. The missing types Fill in missing types from C, in somewhat crude way

  35. strings in C++ • #include<iostream>#include<string>int main() {    std::stringstr; int a; double b;    std::cin >> str >> a >> b; if(std::cin.fail())    {       std::cerr << "input problem\n"; return1;    }    std::cout << "I got: "<< str << ' '   << a << ' ' << b << std::endl; } More about string functions: http://www.cppreference.com/cppstring

  36. Boolean variables • #include<iostream>int main() { int a = 5; boolisZero = (a == 0); • // same conditions if(!isZero && isZero==false && isZero!=true && !!! isZero && a ) {       std::cout << "a is not zero\n";    } }

  37. Enum (C)

  38. User Defined Type - enum • Enumerated data - a set of named constants. • Usage: enum [identifier]{enumerator list} enumSeason { WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN// = WINTER + 3}; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enumColor {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; // 0 1 2 3 4 7 8

  39. enum enumSeason { WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN// = WINTER + 3}; enumSeason curr_season;curr_season= AUTUMN; curr_season= 19;// legal, but ugly, g++: warning intSUMMER; // error, redefinitionintprev_season = SUMMER; // legal, but ugly, g++ warning

  40. Use enum to eliminate magic numbers – alternative to #define

  41. C++-11 enum class enumclassSeason : char{ WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN // = WINTER + 3}; Season curr_season;curr_season= Season::AUTUMN; curr_season= SUMMER; // won’t compile! curr_season= 19; // won’t compile! intprev_season= Season::SUMMER; // won’t compile!

  42. enums – why? • More readable code • Code less error prone • Accessible for debugger • Use of the numerical values is not disabled • bad programming usually!

  43. Overloading Understand and remember. More than syntactic sugar. This is how a lot of stuff works under the hood (e.g. inheritance)

  44. Function overloading - C • #include<stdio.h>void foo() { printf ("foo()\n"); } void foo(int n) { printf ("foo(%d)\n", n); } int main() {    foo(12);    foo(); return0; } Compilation output: Error: Multiple definition of foo

  45. Function overloading – C++ • #include<iostream>void foo() {    std::cout << "foo()\n"; } void foo(int n) {    std::cout<<"foo("<<n<<")\n"; } int main() {    foo(12);    foo(); } Output: Compile, and print: foo(12) foo()

  46. Default parameters • #include<iostream>void foo(int n=5) {    std::cout << n; } int main() {       foo(); } Output: Compile, and print: foo(5)

  47. Overload resolution • Find all functions with same name “candidates”. Let’s call them • Find which have the correct number of arguments - “viable candidates” • Find with best matching arguments. • if • use that function. • else (0 or more than 1): • emit compilation error.

  48. Memory & Arrays (C)

  49. Memory • int main() { char c; int i,j; double x; c i j x

  50. Arrays • Defines a block of consecutive cells • int main() { int i; int a[3];   i a[0] a[1] a[2]

More Related