0d: 00h: 00m: 00s

šŸŽ Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

šŸŽ Get 3 extra months of learning completely FREE

Become a PRO
Bruno Rocha
PRO
3 months ago
Brunocountry asked

How to print a vector?

Saujanya Poudel
Expert
yesterday

1. Displaying All Vector Elements

To display all the contents of a vector, you can use a ranged for loop to iterate through each element and print it out.

Here’s how you can print the contents of the names vector:

#include 
#include 

using namespace std;

int main() {
    vector names;
    names.push_back("Jeremy");
    names.push_back("Jules");
    names.push_back("Howard");

    string inputName; 
    cin >> inputName;

    names.at(1) = inputName;

    // Printing the vector
    for (const string& name : names) {
        cout << name << endl; // prints each name on a new line
    }

    return 0;
}

In the code above, the for loop uses a range-based syntax to iterate through each element in the names vector and print each one. This approach is simple and effective!

2. Displaying Individual Vector Elements

You can display individual vector elements using either the at() method with index or the [] notation with index.

For example:

#include 
#include 

using namespace std;

int main() {
    vector names;
    names.push_back("Jeremy");
    names.push_back("Jules");
    names.push_back("Howard");

    cout << names.at(0) << endl;
    cout << names[1] << endl;
    cout << names.at(2) << endl;
 
    return 0;
}

Important! Since the at() method is safer, you should use this instead of [].

C++
This question was asked as part of the Learn C++ STL course.