在C++中,使用cout
可以輕松地輸出復雜的數據結構。為了實現這一目標,你需要包含iostream
頭文件,并使用命名空間std
。以下是一些常見復雜數據結構的輸出示例:
#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;
}
#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;
}
#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;
}
#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;
}
#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
輸出不同類型的復雜數據結構。你可以根據需要調整這些示例以滿足你的需求。