Ge3ng
Ge3ng

Reputation: 2430

How do I return a vector<T> from a function in c++

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

Upvotes: 4

Views: 1673

Answers (4)

Fred Nurk
Fred Nurk

Reputation: 14212

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?
};

Upvotes: 0

Alexandre C.
Alexandre C.

Reputation: 56976

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);
}

Upvotes: 2

etarion
etarion

Reputation: 17159

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.

Upvotes: 4

peoro
peoro

Reputation: 26060

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;
}

Upvotes: 9

Related Questions