C++中创建异构容器的方法有多种,以下是其中几种常见的方法:
#include <variant>
#include <iostream>
#include <string>
int main() {
std::variant<int, double, std::string> myVariant;
myVariant = 42; // 存储int类型
std::cout << std::get<int>(myVariant) << std::endl; // 输出:42
myVariant = 3.14; // 存储double类型
std::cout << std::get<double>(myVariant) << std::endl; // 输出:3.14
myVariant = "Hello"; // 存储std::string类型
std::cout << std::get<std::string>(myVariant) << std::endl; // 输出:Hello
return 0;
}
#include <any>
#include <iostream>
#include <string>
int main() {
std::any myAny;
myAny = 42; // 存储int类型
std::cout << std::any_cast<int>(myAny) << std::endl; // 输出:42
myAny = 3.14; // 存储double类型
std::cout << std::any_cast<double>(myAny) << std::endl; // 输出:3.14
myAny = "Hello"; // 存储const char*类型
std::cout << std::any_cast<const char*>(myAny) << std::endl; // 输出:Hello
return 0;
}
#include <iostream>
#include <vector>
#include <memory>
class Base {
public:
virtual void print() const = 0;
};
class Derived1 : public Base {
public:
void print() const override {
std::cout << "Derived1" << std::endl;
}
};
class Derived2 : public Base {
public:
void print() const override {
std::cout << "Derived2" << std::endl;
}
};
int main() {
std::vector<std::unique_ptr<Base>> myContainer;
myContainer.push_back(std::make_unique<Derived1>());
myContainer.push_back(std::make_unique<Derived2>());
for (const auto& item : myContainer) {
item->print();
}
return 0;
}
这些方法都可以用于创建异构容器,具体选择哪种方法取决于实际需求和使用场景。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云