I need to write a class using a vector and this is my first time using vectors. But I have looked through several books/web pages and can't see why this thing won't compile.

#include <vector>

template <class el>
class pQ
{
public:

private:
vector<el> a(1);

};

Any ideas. There must be some small syntax issue here I cant see. The error is something along the lines of using a struct that is not defined.

Your problems all stem from this line:

vector<el> a(1);

First and foremost you need to remember that any standard names are in the std namespace. If you don't have a using declaration (using std::vector;) or a using directive (using namespace std;) then you need to qualify the declaration explicitly:

std::vector<el> a(1);

The second problem is that you're trying to call a constructor in a class declaration. Because this isn't executable code, you want to remove the argument list:

std::vector<el> a;

Then you can call the constructor of a in the constructor of pQ:

template <class el>
class pQ
{
public:
  pQ()
    : a ( 1 )
  {}
public:
  std::vector<el> a;
};

Though because vectors grow dynamically, you typically don't need to worry about this and can just rely on push_back working it's magic. Only in extreme cases of performance or if the vector is not likely to change its size do you want to set a base size or preallocate a certain amount of memory.

template <class el>
class pQ
{
public:
  pQ()
    : a ( 1 )
  {}
public:
  std::vector<el> a;
};

QUOTE]

Thanks, that helped some. I am having a few problems though. I couldn't use that exact code snippet due to certain ways the code needs to be formatted. Here is the relevant code. This class is being called as an int.

using namespace std;

template <class el>
class pQ
{
public:
pQ();

private:
vector<el> a;

};

template <class el>
pQ<el>:: pQ()
{
a(1);
}

Is it possible to do it this way? The error is:

no match for call to '(std::vector <int, std:allocator <int> >) (int)

Thanks again.

>Is it possible to do it this way?
No, what I showed you was an initializer list for the class constructor. This list has special properties that allow you to actually initialize variables rather than just assign to them as you would have to in the constructor body. If you do not use the initializer list then the vector will be default constructed and you need to use resize:

template <class el>
class pQ
{
public:
  pQ();

private:
  vector<el> a;

};

template <class el>
pQ<el>:: pQ()
{
  a.resize ( 1 );
}

Thanks Narue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.