π Exploring C++ Step by Step: Printing a Vector with Style
Whether you're just diving into C++ or brushing up on some fundamentals, this simple code snippet is a great example of using standard libraries, vectors, strings, and loops. Let's walk through it together and understand each piece!
π§ The Goal
We want to:
- Store a set of numbers in a vector.
- Store a message in a string.
- Print the message followed by the vector's contents, formatted nicely with commas.
π§± The Building Blocks
#include <vector>
#include <string>
#include <iostream>
Here we include three standard C++ headers:
#include <vector>β For thestd::vectorclass.#include <string>β Forstd::string.#include <iostream>β Forstd::cout.
π Main Function
int main() {
All C++ programs start from the main() function. This is where your program begins executing.
π¦ Declaring and Initializing Variables
const std::vector<int> x{1, 2, 3};
const std::string s{"This is a vector:"};
xis a vector of integers initialized with{1, 2, 3}.sis a string containing the message to print.
π¨οΈ Outputting the Message
std::cout << s << " ";
This prints the message string followed by a space.
π Looping Through the Vector
for (size_t i = 0; i < x.size(); ++i) {
std::cout << x[i];
if (i < x.size() - 1) {
std::cout << ", ";
}
}
We loop through each element of the vector:
size_tis a safe type for indexing.- Each element is printed followed by a comma unless it's the last element.
β Final Touch
std::cout << '\n';
This moves the cursor to the next line after printing the vector.
π And We're Done
return 0;
}
This signals that the program completed successfully.
π₯οΈ Output
This is a vector: 1, 2, 3
Here the result:
#include <vector>
#include <string>
#include <iostream>
int main() {
const std::vector<int> x{1, 2, 3};
const std::string s{"This is a vector:"};
std::cout << s << " ";
for (size_t i = 0; i < x.size(); ++i) {
std::cout << x[i];
if (i < x.size() - 1) {
std::cout << ", ";
}
}
std::cout << '\n';
return 0;
}
π§© Final Thoughts
This snippet demonstrates good C++ practices like:
- Using
constfor safety. - Looping through data structures instead of hardcoding output.
- Clean and user-friendly formatting.
If you are a complete C++ beginner check this post out on how to set up C++ in Visual Studio Code.
Happy coding! β¨
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.