The easy way returning Vector content?

Hello

When I did research about how to cout the content of C++ vectors I bounced on those typical Stackoverflow-hard to understand codes.
I didn't understand anything of it.

Then I tried another few methods and finally the most simplistic one seemed to work:
Code:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

using namespace std;
int main() {
vector<int> myVec;
myVec.push_back(1);

cout<< myVec[0] <<endl;
}

Output:
1


Just like a normal array.
Then my question is, why do people make it so hard/complex to return the content of a vector, while it just also can on the normal way like as with an array?

Just wondering.

Thanks for reading,
Niely
Then my question is, why do people make it so hard/complex to return the content of a vector, while it just also can on the normal way like as with an array?
1) It might be unefficient (if optimiser will not get that index is not changed inside loop).
2) It is non-generic and will work only with vectors (or deques)
3) In some context it will be easier and cleaner to use iterators.
4) It is either consistent with standard library (iterators) or modern programming tendencies (for-each and range loops)

Not saying that index access should not be used. Just you need to know alternatives. Also arrays can be accesssed through iterators too.

additionally range for loops are way cleaner than index access:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> myVec {1, 3, 5, 7, 9, 8, 6, 4, 2, 0,};
    for(auto i: myVec)
        std::cout << i << ' ';
    std::cout << '\n';
}
1 3 5 7 9 8 6 4 2 0 
http://coliru.stacked-crooked.com/a/e9c8ec95dc4e9d9e

Add or remove values from vector and this code will work. Change type of values contained in vector and code will still work. Replace vector with list or set and it still will work without further adjustements.
http://coliru.stacked-crooked.com/a/14ac414b44f460fa
Last edited on
Topic archived. No new replies allowed.