问题描述:

I am creating a generic data structure and I want to return a vector that contains some of the objects in my structure.

I tried

template<class T>

vector<T> DataStructure<T>::getItems(int count)

{

vector<T> items;

for(int i = 0; i < count; i++)

items.push_back(data[i]);

return items;

}

But the compiler says

error: ISO C++ forbids declaration of 'vector' with no type

error: expected ';' before '<' token

网友答案:

vector is not defined.

You need to #include <vector> and to specify its namespace either using std::vector or putting an using namespace std; in your function or at the global scope (this latter suggestion should be avoided).


#include <vector>

template<class T>
std::vector<T> DataStructure<T>::getItems(int count)
{
    std::vector<T> items;
    for(int i = 0; i < count; i++)
        items.push_back(data[i]);      
    return items;
}
网友答案:

It's std::vector, not just vector. Other than that,data is undefined in the snippet. But in general, this is the way to return a vector.

网友答案:

As an complement to @etarion perfect answer, the most idiomatic way to perform your operation is, assuming data is of type T*:

template<class T>
std::vector<T> DataStructure<T>::getItems(int count)
{
    return std::vector<T>(data, data + count);
}
网友答案:

Since getItems' definition must be available through the header anyway, as it is a method of a class template, it is easiest to define it within the class definition:

template<class T>
struct DataStructure {
  std::vector<T> getItems(int count) const {
    assert(0 <= count && count <= data.size());  // don't forget to check count

    // if you must use op[] with data:
    // std::vector<T> items;
    // for(int i = 0; i < count; i++)
    //   items.push_back(data[i]);      
    // return items;

    // if data is a container (using random-access iterators here):
    return std::vector<T>(data.begin(), data.begin() + count);

    // if data is an array:
    // return std::vector<T>(data, data + count);
  }

  std::vector<T> data;  // or is data something else?
};
相关阅读:
Top