//Using g++ and ubuntu.
#include <vector>
using namespace std;
Define a class:
class foo(){
(...)
foo(int arg1, double arg2);
}
Constructor:
foo::foo(int arg1, double arg2){
(...) //arrays whose length depend upon arg1 and arg2
}
I would like to do something like this:
vector<foo> bar(10); //error: no matching function for call to 'foo::foo()'
bar[0] = new foo(123, 4.56);
(...)
An alternative method (which I like less) is to use push_back:
vector<foo> bar; //works
bar.push_back(new foo(123, 4.56)); //throws similar error.
//Omitting the "new" compiles but throws a "double free or corruption (fasttop)" on runtime.
I want different elements of the vector to be constructed differently, so I don't want to use the "Repetitive sequence constructor". What should be done?
Declare a constructor of vector class. Pass a vector object v as a parameter to the constructor. Initialize vec = v. Declare a function show() to display the values of vector.
C++11 also support std::begin and std::end for array, so a vector can also be initialized like static const int arr[] = {10,20,30}; vector<int> vec(begin(arr), end(arr)); .
when you create a vector it gets default initialized, so it's up to you if you want to initialize it with user default values or not. You will always get an empty vector container if you don't initialize it.
Why are you using new
when no dynamic memory needs to be created? Of course using new
will fail, it results in a foo*
when push_back
accepts a foo
. (That's what you have a vector of, after all.)
What's wrong with push_back
? If you want to reserve memory up front, use reserve()
; providing a number in the constructor of vector
makes that many copies of the second parameter (which is implicitly foo()
, which won't work hence your errors), which isn't the same as simply reserving memory.
If doing things correctly (no new
) crashes, the fault is in your code and not vector. You probably haven't written a proper class that manages resources.* (Remember The Big Three, use the copy-and-swap idiom.)
*I say this because you say "//arrays whose length depend upon arg1 and arg2
", which I suspect means you have new[]
in your class somewhere. Without the Big Three, your resource management will fail.
You shouldn't be managing resources anyway, classes have one responsibility. That means it should either be a dynamic array, or use a dynamic array, but not both manage and use a dynamic array. So factor out the resources into their own class, and then make another class (yours) which uses them. A dynamic array is a std::vector
, so you are already done with that. Any time you need a dynamic array, use a vector
; there is never a reason not to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With