【问题标题】:C++ Is it possible to cout a whole vector? [duplicate]C ++是否可以计算整个向量? [复制]
【发布时间】:2015-12-23 11:27:20
【问题描述】:

我需要计算一个向量。不仅仅是它的一个元素,而是整个事情。 例如 std::cout

【问题讨论】:

  • std::copy 是你的朋友。
  • @UlrichEckhardt 上帝没有。
  • std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));

标签: c++ vector


【解决方案1】:

你可以定义一个实用函数,比如

template <typename T>
std::ostream& operator<<(std::ostream& output, std::vector<T> const& values)
{
    for (auto const& value : values)
    {
        output << value << std::endl;
    }
    return output;
}

或者自己迭代

for (auto const& value : values)
{
    std::cout << value << std::endl;
}

【讨论】:

    【解决方案2】:

    是的,这是可能的——如果你为你的向量定义了 operator

    #include <iterator>
    
    template <class T>
    std::ostream& operator<<(std::ostream& out, const std::vector<T>& container) {
       out << "Container dump begins: ";
       std::copy(container.cbegin(), container.cend(), std::ostream_iterator<T>(out, " " ));
       out << "\n";
       return out;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2020-03-20
      • 2015-10-08
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多