溫馨提示×

cout c++怎樣輸出復雜數據

c++
小樊
123
2024-11-30 17:15:50
欄目: 編程語言

在C++中,使用cout可以輕松地輸出復雜的數據結構。為了實現這一目標,你需要包含iostream頭文件,并使用命名空間std。以下是一些常見復雜數據結構的輸出示例:

  1. 數組:
#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Array elements: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}
  1. 結構體:
#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
};

int main() {
    Person p1 = {"Alice", 30};

    cout << "Name: " << p1.name << ", Age: " << p1.age << endl;

    return 0;
}
  1. 類和對象:
#include <iostream>
using namespace std;

class Circle {
public:
    double radius;

    Circle(double r) : radius(r) {}

    double area() {
        return 3.14 * radius * radius;
    }
};

int main() {
    Circle c(5);

    cout << "Radius: " << c.radius << ", Area: " << c.area() << endl;

    return 0;
}
  1. 向量(動態數組):
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};

    cout << "Vector elements: ";
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;

    return 0;
}
  1. 映射(關聯數組):
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> m = {{"apple", 5}, {"banana", 8}, {"orange", 3}};

    cout << "Map elements:" << endl;
    for (auto it = m.begin(); it != m.end(); it++) {
        cout << it->first << ": " << it->second << endl;
    }

    return 0;
}

這些示例展示了如何使用cout輸出不同類型的復雜數據結構。你可以根據需要調整這些示例以滿足你的需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女