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
source share
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
source

This is std::vector , not just vector . In addition, data is undefined in the fragment. But in general, this is a way to return the vector.

+4
source

As a complement to the ideal answer to @etarion, the most idiomatic way of doing your operation is that data is of type T* :

 template<class T> std::vector<T> DataStructure<T>::getItems(int count) { return std::vector<T>(data, data + count); } 
+2
source

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
source

Source: https://habr.com/ru/post/1337195/


All Articles