C++ Learning Community Forum
August 01, 2010, 03:36:42 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Hello. Smiley
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: Regarding vector::insert() and vector::size()  (Read 463 times)
katty
N00b!!1
*
Posts: 3


View Profile
« on: December 09, 2009, 09:51:35 AM »


Hello folks Smiley
M learning basics of vector.. i came across a doubt while writing this program

Code:
struct employee
{
  int id;
   int phone;
   
};

int main()
{

vector<employee> emp;
struct employee temp;
emp.resize(4);

for(i=0;i<4;i++)
{
temp.id =i+2;
temp.phone = i+20;
emp.insert(emp.begin()+i, temp);
}
cout<<"size="<<emp.size();  // my doubt lies here... why did size changed to 8 even though i made it as '4'
return 0;
}


And what I should do to restrict number of elements in vector
i.e if i declare size of vector is 'n' then the size should go beyond 'n'
Please guide me
Logged
shash4evr
Nerd
****
Posts: 74


View Profile
« Reply #1 on: December 09, 2009, 11:27:01 AM »


when you call resize(N) method , it will create copies of objects (in your case strut) until reach the N elements.

therefore when you call size() subsequently , it will give you the size as N unless you insert elements beyond N.

if your requirement is to restrict the number of elements, then i recommend you to go for array implementation, since vector is there for to maintain variable length of elements.

like - employee* p_MyEmployees[NUM_EMP];
Logged
charlie
Is the meadow on fire?
Dr. of C++ology
****
Posts: 730


CsGYh8AacgY


View Profile
« Reply #2 on: December 11, 2009, 07:41:41 PM »

You have two good options here. You could set the size of the vector to 4, and then assign new values to each entry:
Code:
vector<employee> emp(4); // starts with 4 objects

...

// in the loop
emp[i] = temp;
// or
emp.at(i) = temp;
Or you could not set an initial size and just add elements to the vector. I would use push_back instead of insert for that:
Code:
vector<employee> emp; // starts empty

...

// in the loop
emp.push_back(temp);
I'd prefer the second version, because the first creates 4 objects and then ignores them.
Logged
katty
N00b!!1
*
Posts: 3


View Profile
« Reply #3 on: January 18, 2010, 08:58:08 AM »

Thank You folks... now i understood how vector::insert() works 
Logged
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!