It’s been almost two years since I used C++, so I need to brush up on my knowledge of C++ (which wasn’t great to begin with). I am skimming through the book Exploring C++20: The Programmers Introduction to C++ by Ray Lischner byRay Lischner. Here we go!

Arrays and Vectors

Vectors for Arrays

Define an empty vector

include<vector.h>
std::vector<int> data{};

vector is a library type with a well defined intial value, namely, empty, so I could leave it as data;

Read user input and store in the vector. I am used to the append command of Python so C++’s emplace_back command sounds strange to me.

data.emplace_back(x);

I didn’t know that C++ offers a sort command.

include<algorithm.h>
std::ranges::sort(data);

Member functions of vector: front(), back(), size().

Vector of strings:

std::vector<std::string>>

Vector of vectors:

std::vector<std::vector<int>>

Ranges and algorithms

Instead of using data[n], use data.at(n). at() is safer to use. If the index is out of bounds, the program will terminate safely. with [], the program will result in undefined behaviour. It might even run with the bad data, which is worse.

Over the past 30 minutes I was doubting the usefulness of this book because it is written according to C++20, which is probably way too new for my collaboration’s analysis software, so I thought I should take a look at other books. Well, that was not a great idea. I tried Effective Modern C++ and A Tour of C++, Second Edition. The former is way too advanced for me and the latter is unreadable for me. I am (almost) new to C++. The current book is much better for beginners. It’s easy to read. Let’s continue! From now onwards, I won’t go too much into the details because much of the stuff might be too new for my use.

for loop over a vector:

for (std::vector<int>::iterator iter{data.begin()}; iter != data.end(); ++iter)
{
    int element *iter;
    std::cout <<element << '\n';
}

I don’t know why he used std::vector<int>::iterator instead of std::vector<int>. Hmm, it’s been mentioned in the previous paragraph. Read it! Much more about this on Page 73 under the heading ‘Back to Iterators’

Hmm. So, iter is an address(?). Let’s read about Pointers.

Pointers

  • stores the memory addressas its value

  • points to the data type of the same type.

  • string myname('Mo');
    string* authorname = &myname;
    std::cout<<*authorname<<"\n";
    

Okay, iter is a pointer.

Increment and Decrement

  • Prefix (++x): Increment the value first -> x = value after incrementing
  • Postfix (x++): save old value -> increment -> x = old value

Prefix is efficient. Use it unless Postfix is required.

Okay, let’s forget about the decrement operator for now. Moving on!

Enough for today. Next time: Chapter 12.