| | |
How to initialize a vector?
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
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:
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.
C++ Syntax (Toggle Plain Text)
#include<iostream> #include<string> #include<vector> using namespace std; int main() { // here are our original strings in an array of strings // for the sake of this example imagine that strs[] was // passed in as an argument so we don't know upfront how // many strings are in the array string strs[] = {"String1","String2","String3","String4","String5"}; // But before we attempt to reserve some space on a vector, // we need to know how many strings there are..... // trying to count them doing something like this // int count=0; // while (strs[count]) // ++count; // // Would not work as std::string cannot be evaluated like // that...So we actually need to know upfront how many there are // in order to reserve space in the vector. int count=5; // so this value would have to be passed-in too! // reserve 'count' spaces in our vector vector<string> vec(count); // now our vector has enough space to hold all of the strings in the passed-in array.... // so we'll set up a loop to copy strings from the array to the vector: for(int index=0;index<count; ++index) { // This can be used, but it is dangerous //vec[index] = strs[index]; // This is safer..Less likely to cause a crash if you // overstep the mark with index! vec.at(index]=strs[index]; } // Now let's see what the vector contains cout << "The strings in the vector are:" << endl; for(vector<string>::iterator iter = vec.begin(); iter!=vec.end(); iter++) { cout << (*iter) << endl; } // enter any random string to quit! string dummy; getline(cin, dummy); }
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!
Those who understand binary .....
And those who don't!
However, using push_back(), you'd do it like this:
This is by far the preferred way of doing things!
Jas.
C++ Syntax (Toggle Plain Text)
#include<iostream> #include<string> #include<vector> using namespace std; int main() { string strs[] = {"String1","String2","String3","String4","String5"}; // we still need to know how many strings there are int count=5; // no need to reserve any space in the vector 'cause we'll use push_back() std::vector<string> vec; // so lets populate the vector.... for(int index=0;index<count; ++index) { vec.push_back(strs[index]); } // Now let's see what the vector contains cout << "The strings in the vector are:" << endl; for(vector<string>::iterator iter = vec.begin(); iter!=vec.end(); iter++) { cout << (*iter) << endl; } string dummy; getline(cin, dummy); }
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!
Those who understand binary .....
And those who don't!
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
0
#6 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 */
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!
Those who understand binary .....
And those who don't!
0
#7 Oct 9th, 2009
would this do ?
[edit]
Oh, looks like someone already has gotten this answer
[/edit]
C++ Syntax (Toggle Plain Text)
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]
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? 0
#8 Oct 14th, 2009
•
•
•
•
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]
So..typing words in the name... is that the memory direction of that array? You totally lost me on that one
0
#9 Oct 14th, 2009
•
•
•
•
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
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? 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:
Is that it?
C++ Syntax (Toggle Plain Text)
vector<int> v(); // a void v vector vector<int> v(4, 100); // v is 100,100,100,100 vector<int> v(words, words + 3); copy each element of the array words, from the first to the third vector<int> x(v); // x is a copy of v
Is that it?
![]() |
Similar Threads
- 2D Vector && Segfaults (C++)
- How to initialize a vector of pointers? (C++)
- Made my own vector thingy (C)
Other Threads in the C++ Forum
- Previous Thread: Binning alorithm
- Next Thread: how to store input large amout of data ..help over this
| Thread Tools | Search this Thread |
api application array arrays based beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete deploy developer dll dynamiccharacterarray email encryption error file forms fstream function functions game generator getline givemetehcodez graph homeworkhelp homeworkhelper iamthwee ifstream input int java lib list loop looping loops map math matrix memory multiple newbie news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference rpg simple sorting string strings temperature template text tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






