Course week 6 exercises

These submissions are due in course week 6 and they will be discussed on week 7 exercise sessions.

Iterators

All 6 questions concern iterators. In questions 1, 2 and 3 you should select the code that will compute given the task. Unless otherwise specified, the iterator type is std::vector<int>::iterator.

We want to move iterator it forward by 5 positions.
We want an iterator that points to the last item. (In the bookmark analogy, the bookmark would be between the two last books.)
We want to compute the size of the vector.

What does the following code print?

1
2
3
4
5
6
7
8
9
  vector<int> ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  auto iter = ints.begin();
  auto another = iter + 5;
  iter +=3;
  if ( iter < another ){
      cout << *iter;
  } else {
      cout << *another;
  }

What does the following code print?

1
2
3
4
5
6
7
8
9
  vector<int> ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  auto iter = ints.begin();
  auto another = ints.insert(iter, 11);
  iter = ints.begin() + 5;
  if ( iter < another ){
      cout << *iter;
  } else {
      cout << *(another + 2);
  }

What does the following code print?

1
2
3
4
  vector<int> ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  auto iter = ints.begin();
  iter = iter * 3;
  cout << *iter;

STL containers

In each problem, a list of requirements are a given for a data structure. For each problem, select which C++ STL data structure has the best overall runtime efficients for the given requirements. More information about STL data structures can be found from the lecture slides and in the cppreference website

Please note that there are three submissions, but the questions will be randomized for each round.

  1. Elements are added to the end of the data structure, and they are read & removed in reverse order, hence the last element added is the first that will be read and removed.
  1. Elements are added to the data structure, and they are read & removed in the same order, hence the first added element is the first that will be read and removed.
  1. Elements are often added to the data structure. Often it is necessary to go through all the elements in the order in which they were added. Occasionally it is necessary to go through all the elements in increasing order, after which the largest element is removed.
  1. Elements are often added to the data structure. Often there is a need to go through all the elements in increasing order, after which the smallest element is removed.
  1. Elements are often added to the end of the data structure. Seldomly an element is added in the middle in some designated location. Often there is a need to get the i th element (where i varies).
  1. It is often necessary to add an element to the data structure to the left or the right of an element that has just been found. Elements are removed from the end of the data structure.
  1. Elements are often added to the data structure. Often it is necessary to find out, if an element of given value is in the data structure, and then remove the element, if it is found.
  1. Elements are often added to the data structure. Often it is necessary to find out, if an element of given value is in the data structure, and then remove the element, if it is found. Less often it is necessary to go through all the elements in increasing order.
  1. N items are inserted into a container.

    What would be the asymptotic efficiency of the whole insertion, if the container was a list?

  1. Consider again the previous question. What would be the asymptotic efficiency if the container was a set?
  1. A container has N items in arbitrary order. A check is made to see if a certain value is in the container.

    What would be the average efficiency of computing the check, if the container is vector?

  1. Consider again the previous question. What would be the average efficiency if the container was an unordered_set?

Estimating asymptotic efficiency

A+ presents the exercise submission form here.

Student git repositories

First, students should clone their repos. Then, set the upstream. Git repositories are used for both weekly exercises and the course project work.

Hello Gitlab

Description

This exercise guides you through the process of setting up everything so that you can submit the assignment. What we expect you have done before you submit:

  • Find your project repository in Gitlab
  • Clone the repository to your computer
  • Save your SSH keys to Gitlab
  • Make a commit to the repository
  • Push the commit to Gitlab
  • Paste the commit hash to the input below

Detailed Instructions

1. Log into https://course-gitlab.tuni.fi/

Logging in requires TUNI authentication. TUNI hosts course-gitlab service to facilitate your studies and research.

2. Find your project

Your own repository is at: https://course-gitlab.tuni.fi/compcs300-fallYEAR/YOUR_USERNAME If not found, please contact the course personnel.

3. Save your SSH keys

Pulling and pushing is easier and faster when you have saved SSH keys to course-gitlab. The method of generating ssh-key differs from operating system to another, but it is first recommended to check if an ssh-key already exists. There are two instructions, one for Windows and the other for Mac OS + GNU/Linux and other UNIX compatible systems. Please follow the instructions corresponding to your operating system.

Note: ~ refers to the home directory in operating systems. If all operating systems had a user called student, the home directory would be C:\Users\student\ in Windows, /home/student/ in GNU/Linux and /Users/student/ in Mac OS.
After ssh-key has been created, it will be in a hidden folder .ssh within the home directory.

Windows

(recommended) Checking if ssh-key already exists
  1. Open Windows PowerShell
  2. run command Get-Content ~/.ssh/id_rsa.pub
  3. If the command prints something starting with ssh-rsa and does not give an error, ssh key already exists, and you may now copy this key to course-gitlab
Generating ssh-key on Windows
  1. Open Windows PowerShell
  2. run command ssh-keygen
  3. The command now asks for the path where to save the key, just press enter
  4. a passphrase for the key, in this case it is recommended to just leave it empty
  5. the same passphrase is confirmed, so press enter again
  6. the command should state that a key has been saved (it might be phrased as your identification)
  7. To print out the key to copy to course-gitlab run Get-Content ~/.ssh/id_rsa.pub
  8. you may now copy this key to course-gitlab

Mac OS, GNU/Linux and other UNIX-compatible operating systems (with cat and ssh-keygen)

(recommended) Checking if ssh-key already exists
  1. Open terminal
  2. run command cat ~/.ssh/id_rsa.pub
  3. If the command prints something starting with ssh-rsa and does not give an error, ssh key already exists, and you may now copy this key to course-gitlab
Generating ssh-key on Mac OS, GNU/Linux and others
  1. Open terminal
  2. run command ssh-keygen
  3. The command now asks for the path where to save the key, just press enter
  4. a passphrase for the key, in this case it is recommended to just leave it empty
  5. the same passphrase is confirmed, so press enter again
  6. the command should state that a key has been saved (it might be phrased as your identification)
  7. To print out the key to copy to course-gitlab run cat ~/.ssh/id_rsa.pub
  8. you may now copy this key to course-gitlab

All operating systems: save the SSH-key to course-gitlab

Here, one example on GNU/Linux when following instructions

student@linux:~$ cat ~/.ssh/id_rsa.pub
cat: /home/student/.ssh/id_rsa.pub: No such file or directory
student@linux:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/student/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/student/.ssh/id_rsa
Your public key has been saved in /home/student/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:MUNoKtafK9W/02VzWdysHrim4EOhKNXEz/v25Chaijc student@linux
The key's randomart image is:
+---[RSA 3072]----+
|     . ..        |
|      =.         |
|   . = o+      o.|
|  o + . ++      =|
| . o o +So   . .o|
|  . . = +   . *..|
|   . . ooo ..= + |
|    ..E+o.=++ .  |
|    .ooo.++*o    |
+----[SHA256]-----+
student@linux:~$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDVixpMZhpjmBuOn5BLS9/mpCUcSLbwgxIP9/r5o01/
KWxvTnWZS1bGTmJN98DEhLzL+7zWnB3+cqWSGrKKU++G9cy0FnLbJYW4Ip/q18Y04g9RHNcIy+tEwrUA
uCwsRgU0Eg9DPrvRVUmA04ODhA/PxS7kROEly5ryteQqcOmsqDNAg6LjHXUuxb40MUZeZ9fA3/DOlka+
tJJL6XcZ2GEVtRet4BIuEYcfp3ukr1ItwJ9gecEdAA9t/Xy2Q0KdRFd8OvAU+ZGU4GbL9tI3IxyaQCp1
KTCwV21yPUzYVAd82BEmBKvQKgGBgiyGJJEcekqAAVdHglHVpml+LDPjWF+3VRW3GgT918RyRQ676elv
j+NvaHAzh8WpXI61620NwepwFEofCZNkwNCJvGcX2rQcI1m5OJNGnSgpqiKkrvrLffrboOml8GUg/qSE
sJ5z6q9114cNX655bytYeY5e/6T7NWtYVRgg2cJZTTw2DuHQVtsRoObCF2wj8OyXf4H2gV8= student@linux
  • Copy paste the corresponding output from your computer starting from ssh-rsa till the very end.
  • Paste here: https://course-gitlab.tuni.fi/-/profile/keys
  • Paste the key to the textarea
  • Add key button activates. Press it. Your key is now saved. Next, we'll have to clone the repository.

4. Cloning the repository locally

Select a good place for your repo in your computer, and then clone it:

git clone git@course-gitlab.tuni.fi:compcs300-fallYEAR/YOUR_USERNAME.git
During some weekly exercises and the projects, students will commit their changes to the repository to grade it. The grading is done with the git url, like in this exercise. The normal procedure:

git pull  # to get the latest changes (not that crucial if submitting alone)
git commit -m "heapify" -a # -m "message to describe the changes"
# -a for all changes, you can also commit only one file or a dir
git push  # only now the changes are visible in gitlab, and an exercise can be graded

5. Copying the git commit hash

Once you are ready to submit the exercise, copy the hash of your commit to plussa.
The commit hash can be copied from course-gitlab repository webpage or terminal.
Choose the method you prefer and follow its instructions (or both if you want to learn more about git).

Copying the commit hash from course-gitlab webpage

Start by opening your repository webpage, then click the copy commit SHA button to copy the commit hash to the clipboard

Copying git-URL
Copying git commit hash from the copy commit SHA button on course-gitlab repository page
If you want to use an older commit hash, open the commits list (In the figure you would click 42 Commits below the repository name). There you will find all the commits and all the commits will have their respective copy commit SHA buttons.

Copying the commit hash from terminal

When you are in the directory of your git repository, run git log
It will open a text listing as in the example below

      student@linux:~/path/to/repository$ git log
      commit cab9f5b0ae657a321a2af84463ccadc4358dcd16 (HEAD -> main, origin/main, origin/HEAD)
      Author: Student Name 
      Date:   Wed Sep 6 08:47:01 2023 +0300

          Good and descriptive commit message

      commit f8bc013b24fe1caba6aa628517aaf68af47b9775
      Author: Student Name 
      Date:   Wed Sep 6 08:42:57 2023 +0300

          Another good and descriptive commit message

      commit 13aa92cca8407a2acf7f1ab1edea64e18f412116
      Author: Student Name 
      Date:   Tue Sep 5 15:30:01 2023 +0300

          Another good and descriptive commit message

      commit 10ef99cd400a02dbbaf2016cf60fe519680c0def
      Author: Student Name 
      Date:   Tue Sep 5 15:26:16 2023 +0300

      :
      
The commit hashes are now listed for each commit, and it is possible to copy it from there.
Note! If the next terminal prompt didn't pop up and you don't want to scroll the list up and down with arrow keys, press q to quit the listing.

For learning git, TUNI provides a self-study course. If you want the credits for the git course, register to the course in Sisu (COMP.CS.060), too.

6. Grading the exercise - making your first commit

In this course, most of the grading is automated. Exercises that require you to use git will be graded here in plussa. Once you have pushed your changes to the repository, copy your commit hash and paste it in the exercises grader input. If the commit hash is valid, your repository can then be graded once you click on the "Grade my repository" button. The grading process will start shortly after. Most of the time, the grading is done in a few seconds, but sometimes in more complex exercises it can take up quite a few minutes, so please be patient.

Let's give it a shot!

Make a commit to the repository and push it to Gitlab:

  1. Inside the local instance of your repository. Open the file README.md in your preferred editor
  2. Write "Hello gitlab" to the file
  3. Save the file
  4. Use git add to add the file to the staging area:
    git add README.md
  5. Commit the changes to the repository:
    git commit -m "my first commit" -a
  6. Push the commit to Gitlab:
    git push
  7. Copy the commit hash from the terminal or course-gitlab project page
  8. Paste the commit hash to the input below (titled: "Git commit hash of your submission")
  9. Click on the "Grade my repository" button below to receive points for going through this introduction.

A+ presents the exercise submission form here.

Course-upstream to pull new instructions

course-upstream is needed for getting instructions and updates to weekly exercises and assignment. The course personnel will distribute the needed files to students via the upstream, that is student_template_project. After setting up the system, all students need to do is to pull the changes.
Add course-upstream as a git remote both for weekly exercises and final assignments
Now, your personal repositories have been created in course-gitlab.tuni.fi. Initially, your git repository includes files that were present in the repository when you got it and the files you possible have added to it.
In order to get updates, new tests and modifications from the course upstream repository, you have to add the student_template_project as a remote to your own git repository. This way, you can pull from the remote and get the changes in your repo.

The address of the course student repository: git@course-gitlab.tuni.fi:compcs300-fall2023/student_template_project.git
From this point on, let us call it course-upstream. So, course-upstream is the repository where course-personnel updates the tests, and from which students may pull updates to their own repositories.

After you have successfully cloned your own repository to your own computer, you can add the course-upstream to your local remotes like so:

git remote add course-upstream git@course-gitlab.tuni.fi:compcs300-fall2023/student_template_project.git

After adding the remote you can view your remotes by

git remote -v


and you can pull from the course-upstream by

git pull course-upstream main

That tells git to pull latest changes from the course-upstream remote and merge them into your local main branch. It will ask you to make a merge commit message. You most likely should not change it in any way from the default message.

At this stage, it is likely you encounter the following error message:

fatal: Need to specify how to reconcile divergent branches.

In this case, you need to configure Git to merge the remote branch into your local branch:

git config pull.rebase false

In case, the merge still does not succeed because of the error message:

fatal: refusing to merge unrelated histories

add the option:

git pull course-upstream main --allow-unrelated-histories

Now, if what follows is a merge failure:

Automatic merge failed; fix conflicts and then commit the result.

Here's how you can solve the conflicts:

  1. Open Each unmerged file: Open each of the unmerged files listed in a text editor.
  2. Locate and Resolve Conflicts: Look for conflict markers (<<<<<<<, =======, and >>>>>>>). Between the <<<<<<< and ======= will be your changes, and between ======= and >>>>>>> will be the conflicting changes from the merge. Decide which changes to keep, edit the file accordingly, and remove the conflict markers.
  3. Stage the Changes: After you resolve each conflict in a file, stage the file by running
    git add ~filename~
  4. Commit the Changes: After you resolve all conflicts, run
    git commit -m "Merge changes from course-upstream"    
    to commit the changes.

Potential merge conflicts are to be solved manually.

Beware that

git pull

will still pull from your own repository at course-gitlab.tuni.fi and NOT from the course-upstream.

The workflow with git repos is the following:

  • The course personnel adds material to the course-upstream
  • Students get notified in Teams and in Plussa News
  • The students then will pull from the course-upstream so that their repositories are updated to contain the latest stuff

A+ presents the exercise submission form here.

Practise iteration

Iteration

Iteration - short instructions

Update your course repository by pulling latest changes from course-upstream to your repository with the following command: git pull course-upstream main

Inside your repository you should see a directory wk06 with the following contents:

wk06
  ├── iteration.pro
  ├── iteration1.hh
  ├── iteration2.hh
  ├── iteration3.hh
  ├── iteration4.hh
  ├── iteration1.cpp (edit the function in here)
  ├── iteration2.cpp (edit the function in here)
  ├── iteration3.cpp (edit the function in here)
  ├── iteration4.cpp (edit the function in here)
  ├── main.cpp
  └── CLI11.hpp
    

Grader will only copy your iteration*.cpp files. Please do not add any includes to the files.

Your task is to implement four different functions which all take an STL list container as an argument. Then the list is iterated through using STL iterators and depending on the function either all or some of the list items are printed.

All functions must print the list items on the same line separated by only one empty space " " and then at the end of the line one new line. (std::endl) It is OK to print one space after the last list item. Preceding and trailing whitespace characters will be ignored.

The grader will compare the output of your functions to the output of the model solution and therefore it is important that you do not print anything else but the list items.

Functions to implement
# Function name File Expected output for the list: {5, 6, 9, 13, 17, 21, 23, 29}
1 void printAllItems(const list<int>& lst) iteration1.cc
5 6 9 13 17 21 23 29
2 void printEverySecond(const list<int>& lst) iteration2.cc
5 9 17 23
3 void printHalf(const list<int>& lst) iteration3.cc
5 6 9 13
4 void printReverse(const list<int>& lst) iteration4.cc
29 23 21 17 13 9 6 5

Testing your functions

Inside the wk06 directory you can open the qt project file iteration.pro In order to run the program with parameters, you need to either run it in terminal or change the command line parameters from Qt Creator.

Changing the command line parameters in Qt Creator

After opening the project, from the left ribbon menu in Qt Creator, select projects (wrench icon). From the opened menu, on the left part under the Build & Run section select run. You may now find the setting for Command line arguments, you can paste the arguments there.

Running the program

Running tests is simple and the iteration program will print usage instructions if you run it with --help as the only command line argument.

Submitting Your Project to Plussa

A+ presents the exercise submission form here.