How to populate a vector upon construction of object in C++? -
i trying create class has member of type std::vector
, want vector filled number 2 when instance of class created:
#include <vector> using namespace std; class primes{ private: vector <int> myvec; myvec.push_back(2); };
but compiler gives me:
error: ‘myvec’ not name type
class primes{ private: vector <int> myvec; myvec.push_back(2); // <-- can not placed here };
compiler expects there declaration / definition of member or method (member function). can not place there code such myvec.push_back(2);
. must placed inside body of method:
class primes { private: std::vector<int> myvec; public: void addprime(int num) { myvec.push_back(num); } };
or in case want construct instance of primes
vector
contain number 2:
class primes { public: primes() : myvec(std::vector<int>(1, 2)) { } private: std::vector<int> myvec; };
or if need populate vector more of them:
int primes[] = { 1, 2, 3, 5, 7 }; const int pcount = sizeof(primes) / sizeof(primes[0]); class primes { public: primes() : myvec(std::vector<int>(primes, primes + pcount)) { } private: std::vector<int> myvec; };
Comments
Post a Comment