this question is on c++. How can I make an array that, in first row has strings and in second row has doubles? I think it should be void but its not working. Is there any other way? Cheers
4 Answers
You cannot have different types in an array. If you need to have two different types there are several ways you can do that
- You can use a
std::pairlike:std::pair<std::string, double> You can use a
structorclassto wrap the differnt types together like:struct some_name { std::string string_name; double double_name; };You could use a
std::maporstd::unordered_map- You could use 2 separate arrays one for the
std::stingpart and one for thedoublepart - C++11 and beyond also has
std::tuplethat is likestd::pairbut can be used for more than 2 types.
I would also suggest the use of a std::array if you know the size of the array at compile time and a std::vector if the array size will not be known until run-time.
Comments
You can use pair, but you have to give the size of this array.. For example:
std::array<std::pair<std::string, double>, 3> dummy{{"string", 1.1}, {"foo", 2.2}, {"bar", 3.3}};
You can then access the elements using first and second:
dummy[0].first // it is a string (string)
dummy[1].second // it is a double (2.2)
You can also create a struct and have an array of struct..
Comments
You can use:
Sample Code: using Pair
vector <pair <string, double> > test;
test.push_back(make_pair("Age",15.6));
test.push_back(make_pair("Job",5));
cout << test[0].first<<" " << test[0].second;
using structure:
struct str_test{
string name;
double value;
};
str_test temp;
temp.name = "Some";
temp.value = 1.1;
vector<str_test>test;
test.push_back(temp);
cout << test[0].name <<" "<<test[0].value;