0

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

1
  • 1
    "I think it should be void but its not working." What exactly is not working? Have you tried anything? Commented Sep 23, 2015 at 12:46

4 Answers 4

5

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::pair like: std::pair<std::string, double>
  • You can use a struct or class to wrap the differnt types together like:

    struct some_name
    {
        std::string string_name;
        double double_name;
    };
    
  • You could use a std::map or std::unordered_map

  • You could use 2 separate arrays one for the std::sting part and one for the double part
  • C++11 and beyond also has std::tuple that is like std::pair but 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

Use an array of std::pair or your own defined struct/class. Or if you require searching consider using std::map instead.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.