Recommended Answers
Jump to PostUnfortunately 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.
Jump to PostOK, 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:
#include<iostream> #include<string> #include<vector> using namespace std; int main() { // here are our …
Jump to PostHowever, using push_back(), you'd do it like this:
#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 …
Jump to PostBallpark?
#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 …
Jump to PostThe problem with Dave's suggestion is all those strings are now stored in memory twice -- once in the array of std::strings and again in the vector of strings. That could be a problem if the computer is low on memory, or the array contains thousands of strings. If there …
All 18 Replies
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.