943,936 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2625
  • C++ RSS
You are currently viewing page 1 of this multi-page discussion thread
Oct 9th, 2009
0

How to initialize a vector?

Expand Post »
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?
Similar Threads
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 9th, 2009
-7
Re: How to initialize a vector?
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.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,953 posts
since Aug 2005
Oct 9th, 2009
1
Re: How to initialize a vector?
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:
C++ Syntax (Toggle Plain Text)
  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.
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Oct 9th, 2009
0

However.....

However, using push_back(), you'd do it like this:
C++ Syntax (Toggle Plain Text)
  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.
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Oct 9th, 2009
1
Re: How to initialize a vector?
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.
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Oct 9th, 2009
0
Re: How to initialize a vector?
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!
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Oct 9th, 2009
0
Re: How to initialize a vector?
would this do ?

C++ Syntax (Toggle Plain Text)
  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.
Reputation Points: 840
Solved Threads: 594
Senior Poster
firstPerson is offline Offline
3,864 posts
since Dec 2008
Oct 14th, 2009
0
Re: How to initialize a vector?
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
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 14th, 2009
0
Re: How to initialize a vector?
Click to Expand / Collapse  Quote originally posted by neithan ...
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
Reputation Points: 840
Solved Threads: 594
Senior Poster
firstPerson is offline Offline
3,864 posts
since Dec 2008
Oct 14th, 2009
0
Re: How to initialize a vector?
Thank you for the link. What i've understood is you can "construct?" a vector in any of these 4 ways:

C++ Syntax (Toggle Plain Text)
  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?
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Binning alorithm
Next Thread in C++ Forum Timeline: how to store input large amout of data ..help over this





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC