How do I return a vector<T> from a function in c++
I am creating a generic data structur开发者_运维知识库e 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?
};
精彩评论