Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Any type
Possible solution
Note that the implementation you had to refactor does not delete the elements in the vector properly. By using any you don't have to worry no new
and delete
is needed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <any>
#include <vector>
#include <string>
#include <iostream>
using element = std::any;
using namespace std::string_literals;
int main()
{
std::vector<element> vec_of_any;
vec_of_any.emplace_back(1);
vec_of_any.emplace_back(2.0);
vec_of_any.emplace_back(std::vector<int>(2, 5));
vec_of_any.emplace_back("Hello"s);
for (const auto& elem : vec_of_any)
{
if (elem.type() == typeid(int)) {
std::cout << std::any_cast<int>(elem) << std::endl;
}
if (elem.type() == typeid(double)) {
std::cout << std::any_cast<double>(elem) << std::endl;
}
if (elem.type() == typeid(std::vector<int>)) {
const auto& vec = std::any_cast<const std::vector<int>&>(elem);
std::cout << "[";
for(auto i = 0; i < vec.size(); ++i) {
std::cout << vec.at(i);
if (i < (vec.size()-1)) {
std:: cout << ", ";
}
}
std::cout << "]\n";
}
if (elem.type() == typeid(std::string)) {
std::cout << std::any_cast<std::string>(elem) << std::endl;
}
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content