-6

I am trying to get a feel for C++, and I want to either print the contents of a vector, or, to confirm my program is correct, I could add the contents of my vector and print the result.

Here is my code:

#include <iostream>
#include <vector>

using std::vector;
using std::cin;
using std::cout;

int main(){
  int n;
  vector<int> result;
  cin >> n;
  vector<int> numbers(n);
  for(int i = 0; i < n; ++i){
    cin >> numbers[i];
  }
  result = numbers;
  cout << result;
  return 0;
}

I found some solutions online for printing a vector, but I didn't understand what the code was doing, so I am hoping someone can help.

ofithch79
  • 195
  • 1
  • 1
  • 7

2 Answers2

2

As you mentioned "I did not understand what the code is doing", let me briefly describe how to iterate through a container:

The long way:

vector<int> result = { 1,2,3 };

for (vector<int>::iterator it = result.begin(); it != result.end() ; it++) {
    int i = *it;
    cout << i << " ";
}

Each container provides an iterator, which you can think of a pointer moving forward along the elements of the container. begin() returns a pointer to the first element, end() returns a pointer to 1 past the last element. Dereferencing the iterator gives the actual value.

For above long way, with range-based for loops, C++ provides a shorthand notation with about the same meaning (i.e. it makes use of the iterator-concept but is less "clumsy" in notation):

for (auto i : result) {
    cout << i << " ";
}

Try it out; hope it helps.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

you can print the vector content by making a loop the print every index in the vector size

like

for(int i=0;i<numbers.size();i++){
 cout<<numbers[i];
 }

the loop will print every index until the end of the vector

Mohamed Mo'nes
  • 420
  • 3
  • 14