所以基本上我有一个私有(private)的 std::vector<std::string> alloc
在class A
通过公共(public)方法对其进行了一些操作等 std::vector<std::string> allocMethod()
然后这个方法执行return alloc
.该方法在 class B
中调用
在class B
我想打印 allocMethod
的返回值,即 alloc
vector 。这是我的
std::cout << A.allocMethod();
我知道通常人们会使用某种交互器和循环来打印出一个 vector ,但我不认为我可以这样做,因为它是一个正在打印的函数返回值,而不是一个 vector 。
注意:我真的不想只打印出 class A
中的 vector .
有没有办法输出std::vector<string>
结果如上图?
最佳答案
"Note: I reeaaally don't wan't to have to just print out the vector in class A."
如果您想重复使用它,为 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;
}
这应该允许只调用
std::cout << A.allocMethod();
您甚至可以尝试更通用的重载
template<typename T>
std::ostream& operator<<(std::ostream& os,const std::vector<T>>& vs) {
for (const auto& s : vs) {
os << s << " ";
}
return os;
}
关于c++:打印函数返回的字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452699/