June 5th, 2011 01:58 PM
#1
std::vector as a static member
Hello,
I have a class with a vector as a static member:
Code:
class MyClass
{
static std::vector<int> my_vector;
}
I then wish to initialize the vector in the .cpp file in global scope:
Code:
std::vector<int> my_vector = std::vector<int>(10);
my_vector[0] = 5;
But this gives me some errors. How can I initialize the values of my_vector? Thanks.
June 5th, 2011 02:40 PM
#2
Re: std::vector as a static member
Originally Posted by
ejohns85
Hello,
I have a class with a vector as a static member:
Code:
class MyClass
{
static std::vector<int> my_vector;
}
I then wish to initialize the vector in the .cpp file in global scope:
Code:
std::vector<int> my_vector = std::vector<int>(10);
my_vector[0] = 5;
But this gives me some errors. How can I initialize the values of my_vector? Thanks.
What are the errors? Also, please post compilable code so we can see what you're doing.
Code:
#include <vector>
class MyClass
{
static std::vector<int> my_vector;
};
//....
// In one CPP file outside of any function:
std::vector<int> MyClass::my_vector(10);
The code below is not initialization -- it is assignment
Therefore it must be done within a function.
Regards,
Paul McKenzie
June 5th, 2011 05:41 PM
#3
Re: std::vector as a static member
Code:
class Foo
{
public:
static std::vector<int> v;
};
// Foo.cpp
std::vector<int> Foo::v = std::vector<int>(5);
...
int main()
{
...
Foo::v.push_back(3);
Foo::v.push_back(1);
Foo::v.push_back(8);
Foo::v.push_back(6);
Foo::v.push_back(2);
...
std::cout << "v[0] = " << v[0] << std::endl;
}
June 6th, 2011 09:26 AM
#4
Re: std::vector as a static member
You can use Boost.Assign:
Code:
std::vector<int> Foo::v = boost::assign::list_of(5)(10)(15)(20); // as long as you like
If you don't want that dependency, this will produce the same result:
Code:
vector<int> initializeVector()
{
vector<int> v;
v.push_back(5);
v.push_back(10);
v.push_back(15);
v.push_back(20);
return v;
}
std::vector<int> Foo::v = initializeVector();
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width
Bookmarks