Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 533
Ge3ng Avatar asked Dec 06 '22 23:12

Ge3ng


1 Answers

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;
}
like image 66
peoro Avatar answered Dec 09 '22 11:12

peoro