vector issue

This is a discussion on vector issue within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <vector> using namespace std; typedef vector<int> intVector; int main() { intVector vInt1(5); vInt1[0]=1; cout<<vInt1.size()<<endl; cout<<vInt1.capacity(); return ...

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    712

    vector issue

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    typedef vector<int> intVector;
    
    int main()
    {
    	intVector vInt1(5);
    	vInt1[0]=1;
    	cout<<vInt1.size()<<endl;
    	cout<<vInt1.capacity();
    	return 0;
    }
    Output is:
    5
    5
    which is supprising (at least for me)
    I was expecting 1 5
    Druring compiling I get two following warnings:

    conversion from 'size_t' to 'unsigned int', possible loss of data

    both for cout
    I can get rid of them by casting to unsigned int
    If someone can explain output.
    whati is the difference between size() and capacity()

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,821
    size() should give the number of elements, and capacity() the max number before more space must be allocated.

    Maybe this would be clearer?

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    typedef vector<int> intVector;
    
    int main()
    {
    	intVector vInt1;
    	vInt1.reserve(5);
    	vInt1.push_back(1);
    	vInt1.push_back(0);
    	cout<<vInt1.size()<<endl;
    	cout<<vInt1.capacity();
    
    	return 0;
    }
    I suspect that the reason for the warning is that the constructor doesnt accept a single integer as an argument.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    712
    It's working, thanks man

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21