mawandm
mawandm

Reputation: 13

Why is the code printing the last std::cout?

using namespace std;

template<typename T>
int f(vector<T> &v){
    return v.size();
}

template<typename T>
class B{
public:
    int size(){
        return v.size();
    };
private:
    vector<T> v;
};

int main(int argc, char** argv) {

    B<string> b;

    vector<string> v;

    for(int i=0; i<f<string>(v)-1; i++)
        std::cout << "using fn template" << endl;

    for(int i=0; i<b.size()-1; i++)
        std::cout << "using class B" << endl;

    for(int i=0; i<v.size()-1; i++)
        std::cout << "done" << endl; //Why is this printing???
    return (EXIT_SUCCESS);
}

Upvotes: 1

Views: 146

Answers (1)

Jonathan M Davis
Jonathan M Davis

Reputation: 38287

vector's size() function returns a value of type size_t which is unsigned. So, if size() returns 0 and you subtract 1 from it, you're going to get a very large number rather than -1. That very large number will be greater than 0 and the condition i < v.size() - 1 will therefore be be true since i is 0.

EDIT:

I should probably add that normally when iterating over an array or a vector, you iterate as long as your index is less than the size of the array or vector rather than size - 1.

 for(int i = 0; i < v.size(); ++i)
    std::cout << "done" << endl;

would likely be what you really want to do. Even if you used (int)v.size() - 1 to get rid of the signed vs unsigned issue, the loop would stil be wrong because you'd miss the last element in cases where you actually had elements in the vector.

Upvotes: 13

Related Questions