C++20 sections · 1024 units
Open in Course

Problem: Building Dynamically

Practice with vectors

I'll show you how to build a vector based on user input at runtime. Start with an empty vector v and ask how many elements. Read the count with int n; cin >> n. Then loop n times with for(int i = 0; i < n; i++) and inside read int x; cin >> x; v.push_back(x).

The vector grows as you add each element. If the user enters non-numeric input, cin fails and the loop breaks early. Always validate input with cin.fail() checks or use try-catch blocks.

This pattern works for reading data from files or network sources too.