C ++: print string vector returned by function
So essentially I have a private std::vector<std::string> alloc
in class A
that has some manipulation etc. done on it by a public method std::vector<std::string> allocMethod()
and that method then executes return alloc
. The method is called inclass B
Q class B
I want to print the return value allocMethod
, i.e. vector alloc
. This is what I have
std::cout << A.allocMethod();
I know it is usually possible to use some kind of interpreter and loop to print the vector, but I don't think I can do that as this is the return value of the functions, which is not actually printed by the vector.
Note. I reeaaally don't want to just print the vector into class A
.
Is there a way to output the result std::vector<string>
as shown above?
source to share
"Note: I don't want to just print the vector in class A."
As you want to reuse this, it may be wise to provide an appropriate overload of the output statement for std::vector<std::string>
std::ostream& operator<<(std::ostream& os,const std::vector<std::string>>& vs) {
for (const auto& s : vs) {
os << s << " ";
}
return os;
}
This should let you just call
std::cout << A.allocMethod();
You can even try more general overload
template<typename T>
std::ostream& operator<<(std::ostream& os,const std::vector<T>>& vs) {
for (const auto& s : vs) {
os << s << " ";
}
return os;
}
source to share