Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 超载<&书信电报;c+的运算符+;stl容器_C++_Stl_Ofstream - Fatal编程技术网

C++ 超载<&书信电报;c+的运算符+;stl容器

C++ 超载<&书信电报;c+的运算符+;stl容器,c++,stl,ofstream,C++,Stl,Ofstream,我希望我可以使用cout打印set/vector/map的内容。输出STL容器最简单的方法是 std::copy(cont.begin(), cont.end(), std::ostream_iterator<Type>(std::cout, " ")); 复制(继续开始(),继续结束(), std::ostream_迭代器(std::cout,“”); 其中Type是cont元素的类型(例如,如果cont是std::vector类型,则Type必须是int)

我希望我可以使用cout打印set/vector/map的内容。输出STL容器最简单的方法是

std::copy(cont.begin(), cont.end(),
          std::ostream_iterator<Type>(std::cout, " "));
复制(继续开始(),继续结束(), std::ostream_迭代器(std::cout,“”); 其中
Type
cont
元素的类型(例如,如果
cont
std::vector
类型,则
Type
必须是
int


当然,您可以使用任何ostream来代替std::cout。

在C++11中,您可以使用基于范围的
来执行以下操作:

for (auto& i: container)  cout << i << "  ";
cout << endl;

for(auto&i:container)cout转储容器的最简单方法可能就是使用
std::copy()
。例如,我通常使用如下内容:

template <typename C>
std::string format(C const& c) {
    std::ostringstream out;
    out << "[";
    if (!c.empty()) {
        std::copy(c.begin(), --c.end(),
            std::ostream_iterator<typename C::value_type>(out, ", "));
            out << c.back();
    }
    out << "]";
    return out.str();
}
模板
标准::字符串格式(C常量和C){
std::ostringstream out;
出来

stl设计者实现起来似乎并不困难:假设你看起来像这样吗

#include <iostream>
#include <set>

template <typename T>
std::ostream& operator<< (std::ostream& os, const std::set<T>& s)
{
    for( auto i: s ) {
        os << i << " ";
    }
    return os;
}
#包括
#包括
模板

std::ostream&operator调用
container\u-Type::value\u-Type
@ildjarn:但是您仍然必须指定
container\u-Type
它,除非您位于容器类型依赖的模板内(但它是
typename-container\u-Type::value\u-Type
),最有可能包含
Type
。但是,在C++11中,您可以编写
decltype(cont)::value\u Type
(同样,可能在模板中使用
typename
)。
std::set<int> my_set = { 11, 12, 13 };

std::cout << my_set << std::endl;