0

I was studying the library in C++ and I can't understand why my code isn't working... Can you help me please?

void Vect_Visualizza (vector<int> vect) {
     for (auto it = vect.begin(); it != vect.end(); ++it)
         cout << vect.at(it) << " ";  
}

2 Answers2

1

Very slight change.

void Vect_Visualizza (vector<int> vect) {
     for (auto it = vect.begin(); it != vect.end(); ++it)
         cout << *it << " ";  
}

Think of the iterator as a pointer, not an index. begin() and end() return iterators. You'll want to read about them. They're confusing at first.

You can also do this:

for (int &i: vect) {
    cout << i << endl;
}

Which is a lot easier unless you really, really need the iterator itself.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
0
V.at(i) is same as V[i]

so it fails in your case because you are trying to use at() with iterator,which is wrong. at() function expects an integer input, which is the index of the element we intend to access.

consider the code below:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int>v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    cout<<"indexed output: "<<v[1]<<"\n";
    cout<<"output using at: "<<v.at(2)<<"\n";
}

output is:

indexed output: 2
output using at: 3

from this we can observe that using at() is same as indexed access.

Iterator works similar to pointer,hence you can write

cout<<*it
  • 1
    Please don't suggest to [`#include`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h), better, don't use it yourself. Forget you can do it. Especially in combination with [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) (which is bad practice too) it has a tendency to blow things up. – Lukas-T Mar 21 '21 at 15:16
  • 1
    Secondly: What is this code supposed to show? You say _"from this we can observe that using at() is same as indexed access."_ - but the code doesn't even use `at()`. Typo? Also you can't really observe that. You _can_ observe that `at()` _can_ be used with an index. You _can't_ observe that it _can't_ work with an iterator. (It doesn't work with an iterator because the standard says so) – Lukas-T Mar 21 '21 at 15:20
  • @churill yes,sorry that was a typo. instead of v[2], I was supposed to write v.at(2). Coming to #include I only use it when I'm doing competitive programming. For everything else, I use the required header files. I just made changes to pre existing code on my editor hence #include. Thank you for inofrming, I'll make the required edits. – Ram Prabodh Induri Mar 22 '21 at 20:16
  • @churill yes, I have mentioned in the answer that using at() with iterator is wrong.I probably should have mentioned that it only accepts index(numerical ) as input. Thank you for your inputs. – Ram Prabodh Induri Mar 22 '21 at 20:20