PRO
Bruno
asked

Expert
Saujanya Poudel answered
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.








