How to initialize a vector?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2009
Posts: 65
Reputation: neithan is an unknown quantity at this point 
Solved Threads: 2
neithan's Avatar
neithan neithan is offline Offline
Junior Poster in Training

How to initialize a vector?

 
0
  #1
Oct 9th, 2009
I want a vector<string> with some values by default. I wanted to do something like char **strings = {"bla", "blo"}

How to do it with vector<> without using repeated push_backs?
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 15,484
Reputation: Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute 
Solved Threads: 1478
Team Colleague
Featured Poster
Ancient Dragon's Avatar
Ancient Dragon Ancient Dragon is offline Offline
Still Learning
 
-7
  #2
Oct 9th, 2009
Unfortunately AFAIK push_back is the only way to initialize it. The vector is a single object, not an array of objects, so an initialization list is not possible.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 330
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 59
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz
 
1
  #3
Oct 9th, 2009
OK, push_back definitely is the safest way of populating a vector. However, the method I'm about to show is not particularly good practice, but it can be done and it does have it's uses:
  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4.  
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10. // here are our original strings in an array of strings
  11. // for the sake of this example imagine that strs[] was
  12. // passed in as an argument so we don't know upfront how
  13. // many strings are in the array
  14. string strs[] = {"String1","String2","String3","String4","String5"};
  15.  
  16. // But before we attempt to reserve some space on a vector,
  17. // we need to know how many strings there are.....
  18. // trying to count them doing something like this
  19. // int count=0;
  20. // while (strs[count])
  21. // ++count;
  22. //
  23. // Would not work as std::string cannot be evaluated like
  24. // that...So we actually need to know upfront how many there are
  25. // in order to reserve space in the vector.
  26. int count=5; // so this value would have to be passed-in too!
  27.  
  28. // reserve 'count' spaces in our vector
  29. vector<string> vec(count);
  30.  
  31. // now our vector has enough space to hold all of the strings in the passed-in array....
  32. // so we'll set up a loop to copy strings from the array to the vector:
  33. for(int index=0;index<count; ++index)
  34. {
  35. // This can be used, but it is dangerous
  36. //vec[index] = strs[index];
  37.  
  38. // This is safer..Less likely to cause a crash if you
  39. // overstep the mark with index!
  40. vec.at(index]=strs[index];
  41. }
  42.  
  43. // Now let's see what the vector contains
  44. cout << "The strings in the vector are:" << endl;
  45.  
  46. for(vector<string>::iterator iter = vec.begin(); iter!=vec.end(); iter++)
  47. {
  48. cout << (*iter) << endl;
  49. }
  50.  
  51. // enter any random string to quit!
  52. string dummy;
  53. getline(cin, dummy);
  54. }

So vectors can be initialised in this way and this way of doing things can be useful, or may even be necessary from time to time, but you must know exactly how much space you need to reserve in the vector upfront. If you don't reserve enough space in the vector, then your program's almost certainly gonna crash!

But do use push_back wherever possible!
If you were to try to add more items once the vector was initialised in this way, I'd almost certainly use push_back!!

Cheers for now,
Jas.
Last edited by JasonHippy; Oct 9th, 2009 at 1:09 pm.
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 330
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 59
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz

However.....

 
0
  #4
Oct 9th, 2009
However, using push_back(), you'd do it like this:
  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string strs[] = {"String1","String2","String3","String4","String5"};
  10. // we still need to know how many strings there are
  11. int count=5;
  12.  
  13. // no need to reserve any space in the vector 'cause we'll use push_back()
  14. std::vector<string> vec;
  15.  
  16. // so lets populate the vector....
  17. for(int index=0;index<count; ++index)
  18. {
  19. vec.push_back(strs[index]);
  20. }
  21.  
  22. // Now let's see what the vector contains
  23. cout << "The strings in the vector are:" << endl;
  24.  
  25. for(vector<string>::iterator iter = vec.begin(); iter!=vec.end(); iter++)
  26. {
  27. cout << (*iter) << endl;
  28. }
  29.  
  30. string dummy;
  31. getline(cin, dummy);
  32. }

This is by far the preferred way of doing things!

Jas.
Last edited by JasonHippy; Oct 9th, 2009 at 1:17 pm.
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 4,398
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 245
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c
 
1
  #5
Oct 9th, 2009
Ballpark?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
   string init[] = {"one", "two", "three", "four", "five" };
   vector<string> vec(init, init + sizeof init / sizeof *init);
   copy(vec.begin(), vec.end(), 
        ostream_iterator<string>(cout, "\n"));
   return 0;
}

/* my output
one
two
three
four
five
*/
Last edited by Dave Sinkula; Oct 9th, 2009 at 1:47 pm.
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 330
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 59
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz
 
0
  #6
Oct 9th, 2009
Originally Posted by Dave Sinkula View Post
Ballpark?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
   string init[] = {"one", "two", "three", "four", "five" };
   vector<string> vec(init, init + sizeof init / sizeof *init);
   copy(vec.begin(), vec.end(), 
        ostream_iterator<string>(cout, "\n"));
   return 0;
}

/* my output
one
two
three
four
five
*/
Of course!
Good thinking...Dave, I'd not thought of that!
Nice use of the copy algortihm too...I'd forgotten about that little STL gem!
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 1,336
Reputation: firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice 
Solved Threads: 166
firstPerson's Avatar
firstPerson firstPerson is online now Online
Nearly a Posting Virtuoso
 
0
  #7
Oct 9th, 2009
would this do ?

  1. string words[3] = {"hello","olla","namesta"};
  2. vector<string> vec(words,words+3);
  3.  
  4. for(int i = 0; i < vec.size(); i++)
  5. cout<<words[i]<<endl;

[edit]
Oh, looks like someone already has gotten this answer
[/edit]
Last edited by firstPerson; Oct 9th, 2009 at 5:01 pm.
1) What word becomes shorter if you add a letter to it? 
      [ Solved by : niek_e, Paul Thompson, SgtMe, murtan, xavier666, jonsca]
2) What does this sequence  equal to :  (.5u - .5a)(.5u-.5b)(.5u-.5c) ...
      [*solved by : murtan, xavier666]
3) What is the 123456789th prime numer?
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 65
Reputation: neithan is an unknown quantity at this point 
Solved Threads: 2
neithan's Avatar
neithan neithan is offline Offline
Junior Poster in Training
 
0
  #8
Oct 14th, 2009
Originally Posted by firstPerson View Post
would this do ?

	string words[3] = {"hello","olla","namesta"};
	vector<string> vec(words,words+3);

	for(int i = 0; i < vec.size(); i++)
		cout<<words[i]<<endl;

[edit]
Oh, looks like someone already has gotten this answer
[/edit]
I though it was vector<type> name(lenght or size, init values);

So..typing words in the name... is that the memory direction of that array? You totally lost me on that one
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 1,336
Reputation: firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice firstPerson is just really nice 
Solved Threads: 166
firstPerson's Avatar
firstPerson firstPerson is online now Online
Nearly a Posting Virtuoso
 
0
  #9
Oct 14th, 2009
Originally Posted by neithan View Post
I though it was vector<type> name(lenght or size, init values);

So..typing words in the name... is that the memory direction of that array? You totally lost me on that one
Vectors has many constructors. See here, Link
1) What word becomes shorter if you add a letter to it? 
      [ Solved by : niek_e, Paul Thompson, SgtMe, murtan, xavier666, jonsca]
2) What does this sequence  equal to :  (.5u - .5a)(.5u-.5b)(.5u-.5c) ...
      [*solved by : murtan, xavier666]
3) What is the 123456789th prime numer?
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 65
Reputation: neithan is an unknown quantity at this point 
Solved Threads: 2
neithan's Avatar
neithan neithan is offline Offline
Junior Poster in Training
 
0
  #10
Oct 14th, 2009
Thank you for the link. What i've understood is you can "construct?" a vector in any of these 4 ways:

  1. vector<int> v(); // a void v vector
  2. vector<int> v(4, 100); // v is 100,100,100,100
  3. vector<int> v(words, words + 3); copy each element of the array words, from the first to the third
  4. vector<int> x(v); // x is a copy of v

Is that it?
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC