c++:打印函数返回的字符串 vector

标签 c++ vector cout

所以基本上我有一个私有(private)的 std::vector<std::string> allocclass 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/

相关文章:

matlab - 从向量 MATLAB 中删除连续的重复项

c++ - 不能 push_back 到 vector - 没有给出过载错误

c++ - 当循环失败时,读取 int 和 string C++

c++ - BigInteger 实现,进位不符

c++ - 我如何定义一个模板类来给出类型的指针深度/级别?

c++ - 了解 OPT 算法

c++ - 如何在不邀请 future 对象切片的情况下实现 ICloneable

c++ - 使用 .get() 一次读取一个字节

c++ - 当下一行出现总线错误时对 cout 感到好奇

c++ - 设置小数点前数字的精度?