Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.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++_Ostream - Fatal编程技术网

C++ 输出以空格分隔的列表

C++ 输出以空格分隔的列表,c++,ostream,C++,Ostream,我是重载运算符 但是这可能不是一个好主意,'\b'是否可以与其他类型的ostream配合使用 您完全正确地认为这不是一个好主意:“\b”在控制台模式下运行良好,但它不能很好地与其他流(如文件)配合使用 更好的方法是首先不输出额外的空间: std::ostream& operator<< (std::ostream &os, const MyContainer &v) { os << "["; auto first = true;

我是重载运算符 但是这可能不是一个好主意,
'\b'
是否可以与其他类型的
ostream
配合使用

您完全正确地认为这不是一个好主意:
“\b”
在控制台模式下运行良好,但它不能很好地与其他流(如文件)配合使用

更好的方法是首先不输出额外的空间:

std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
    os << "[";
    auto first = true;
    for (const auto &i : v) {
        if (!first) {
            os << " ";
        } else {
            first = false;
        }
        os << i;
    }
    os << "]";
    return os;
}

std::ostream&operator一个简单实用的解决方案是在范围循环之前添加一个空格:

std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
    os << "[ "; // <--
    for (const auto &i : v) {
        os << i << " ";
    }
    os << "]";
    return os;
}

MyContainer c{1,2,3};
std::cout<<c<<std::endl;

std::ostream&operatorcompiler最终应该支持(GCC将在第6版中提供),在此之前,您必须推出自己的解决方案或使用boost。
ostream\u迭代器显然无法解决问题。这是愚蠢的行为。@Potatosatter哎呀,你是对的,我想我曾经遇到过这种愚蠢的行为,但我总是忘记它。谢谢
std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
    os << "[ "; // <--
    for (const auto &i : v) {
        os << i << " ";
    }
    os << "]";
    return os;
}

MyContainer c{1,2,3};
std::cout<<c<<std::endl;