如何解决如何为C ++设置一种以上的数据类型?
尝试学习来自Python的C ++,在python中,一组可以有多种类型。如何在C ++中做到这一点?我专门尝试设置一个同时包含整数和字符串的集合。例如:
#include <set>
#include <string>
using namespace std;
int main() {
set<int,string> s;
s.insert(1);
s.insert("string");
}
解决方法
容器中具有多种类型的元素称为异构容器。
C ++从C ++ 17开始支持使用std::any(可以保存任何类型),或者当您想自己定义可能的类型时,可以使用as EOF said的std::variant。 >
以下是使用std::any_cast的std::any
的演示:
#include <any>
#include <iostream>
#include <list>
#include <map>
#include <set>
int main()
{
std::list<std::any> any_list;
int myInt = 1;
std::string myString("I'm a string");
using MapType = std::map<std::list<int>,std::string>;
MapType myMap;
struct CustomType {
void* pointer;
};
any_list.emplace_back(std::any());
any_list.emplace_back(myInt);
any_list.emplace_back(myString);
any_list.emplace_back(myMap);
any_list.emplace_back(CustomType());
// To show the awesome power of std::any we add
// the list as an element of itself:
any_list.emplace_back(any_list);
for(auto& element: any_list) {
if(!element.has_value()) {
std::cout << "Element does not hold a value" << std::endl;
continue;
}
if (int* someInt = std::any_cast<int>(&element)) {
std::cout << "Element is int: " << *someInt << '\n';
} else if (std::string* s = std::any_cast<std::string>(&element)) {
std::cout << "Element is a std::string: " << *s << '\n';
} else if (std::any_cast<MapType>(&element)) {
std::cout << "Element is of type MapType\n";
} else if (std::any_cast<CustomType>(&element)) {
std::cout << "Element is of type CustomType\n";
} else {
std::cout << "Element is of unknown but very powerful type\n";
}
}
}
这将产生输出:
Element does not hold a value
Element is int: 1
Element is a std::string: I'm a string
Element is of type MapType
Element is of type CustomType
Element is of unknown but very powerful type
执行此操作的C ++ 17之前的方法显然是带有手动类型信息和struct
的{{1}}。
请注意,我使用void*
代替了std::list
,因为默认情况下std::set
没有定义std::any
。这可以通过定义自己的比较谓词来解决。
我的个人观点是,通常当您认为要使用异构容器时,值得重新评估设计并坚持使用普通的均匀容器,但是如果需要,它就在那里:-)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。