tags:

views:

101

answers:

1
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);
}
+13  A: 

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.

Jonathan M Davis
+1 for correct. (The -1 on your size() is weird, you've got that already via the the use of < instead of <=.)
Greg D
Modern compilers should warn about this, e.g. g++ with `-Wall` prints “warning: comparison between signed and unsigned integer expressions.” @mawandm: When compiling, enable as many warnings as possible and reasonable. For example, I usually run g++ with `-Wall -Wextra -Wconversion -Wunused`.
Philipp
All I need is the first n-1 elements but use the n(th) element within the loop using v.at(i+1). That is why I need to loop to v.size() - 1
mawandm