vj11100
vj11100

Reputation: 13

Error during the usage of of size() function in vectors

So I've started learning vectors for the first time and wrote a simple program which goes like this:

#include <iostream> 
#include <vector> 
using namespace std; 
int main() 
{ 
    vector<int> g1; 
    int n;
    cout<<"enter values"<<endl;
    do
    {
        cin>>n;
        g1.push_back(n);
    } while (n);
    cout<<"Vector values are: "<<endl;
    for(auto i=g1.begin(); i<g1.size();i++)
    cout<<*i<<endl;
} 

When I try executing it, an error shows up saying "type mismatch" at the g1.size() part. Why exactly does this happen? I used the auto keyword for the iterator involved and assumed there wouldn't be any problem?

Upvotes: 0

Views: 358

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 598414

g1.begin() returns an iterator to the 1st element, whereas g1.size() returns the number of elements. You can't compare an iterator to a size, which is why you are getting the error. It has nothing to do with your use of auto, it has to do with you comparing 2 different things that are unrelated to each other.

You need to change your loop to compare your i iterator to the vector's end() iterator, eg:

for(auto i = g1.begin(); i != g1.end(); ++i)
    cout << *i << endl;

Or, simply use a range-based for loop instead, which uses iterators internally:

for(auto i : g1)
    cout << i << endl;

Otherwise, if you want to use size() then use indexes with the vector's operator[], instead of using iterators, eg:

for(size_t i = 0; i < g1.size(); ++i)
    cout << g1[i] << endl;

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76523

There are at least three ways to iterate through the contents of a vector.

You can use an index:

for (int i = 0; i < vec.size(); ++i)
    std::cout  << vec[i] << '\n';

You can use iterators:

for (auto it = vec.begin(); it != vec.end(); ++it)
    std::cout << *it << '\n';

You can use a range-based for loop:

for (auto val : vec)
    std::cout << Val <<'\n';

The latter two can be used with any container.

Upvotes: 2

Klaus
Klaus

Reputation: 25663

That is the bad side of using auto. If you have no idea what the result of auto is, you get no idea why it is something totally different you expect!

std::vector::begin delivers a std::vector::iterator and you can't compare it against an size_type value which is a result of std::vector::size. This type is typically std::size_t

You have to compare against another iterator which is the representation of the end of the vector like:

for(auto i = g1.begin(); i != g1.end(); i++)

Upvotes: 2

Related Questions