我如何简单地打印矢量?

时间:2016-12-22 22:24:19

标签: c++ vector

如果我有这样的矢量:

struct vector3D {
    float x;
    float y;
    float z;
};

vector3D aVector = { 3.4, 4.4, 9.3 }; // my vector

我如何cout aVector到控制台?

1 个答案:

答案 0 :(得分:5)

您可以重载插入操作符<<以用于对象:

struct vector3D {
    float x;
    float y;
    float z;
    friend ostream& operator<<(ostream& out, vector3D rhs){
            out << "( " << rhs.x << ", " << rhs.y << ", " << rhs.z << " )" << endl;
            return out; 
    }
};

现在您可以使用cout打印对象值:

int main(){
    vector3D v = {10, 20, 30};
    cout << v << endl;
}