First, add the ubuntu-toolchain-r/test PPA to your system with:
sudo apt install software-properties-common
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
Install the desired GCC and G++ versions by typing:
sudo apt install gcc-7 g++-7 gcc-8 g++-8 gcc-9 g++-9