How to return a vector <T> from a function in C ++
I am creating a general data structure and I want to return a vector containing 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 ++ prohibits declaring 'vector' without type
error: expected ';' before '<' marker
+4
4 answers
vector not defined.
You need #include <vector> and specify its namespace either using std::vector , or put using namespace std; into your function or global scope (this last sentence 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; } +8
Since the definition of getItems must be accessible through the header, since it is a class template method, it is easiest to define it in 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? }; 0