1

I am quite new to C++ but am familiar with a few other languages. I would like to use a data type similar to a Java ArrayList, an Objective-c NSMutableArray or a Python array, but in C++. The characteristics I am looking for are the possibility to initialize the array without a capacity (thus to be able to add items gradually), and the capability to store multiple datatypes in one array.

To give you details of what I want it for is to read data from different tables of a mysql db, without knowing the number of fields in the table, and being able to move this data around. My ideal data type would allow me to store something like this:

idealArray = [Bool error,[string array],[string array]];

where the string arrays may have different sizes, from 1 to 20 in size (relatively small).

I don't know if this is possible in C++, any help appreciated, or links towards good ressources.

Thanks

4 Answers 4

2

The standard dynamically sized array in C++ is std::vector<>. Homogeneous containers doesn't exist unless you introduce indirection, for this you can use either boost::variant or boost::any depending on your needs.

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

Comments

1

You may use structure or class to store (named) multiple data types together, such as:

class Record
{
   bool _error;
   vector<string> _v1;
   vector<string> _v2;
};
vector<Record> vec;

or std::tuple to store (unnamed) multiple data types, e.g.

vector<tuple<bool, vector<string>, vector<string> > > vec;

Comments

1

I would suggest using a std::vector from the STL. However, note that C++ does not have a container that can contain multiple data types. There are multiple ways to simulate this behaviour though:

  1. Derive all the "types" that you want to store from a certain "Base_type". Then store the items in the vector as std::vector<Base_type*>, but then you would need to know which item is where and the type to (dynamic)cast to, if the "types" are totally different.
  2. Use something like std::vector<boost::any> from the boost library (but noticing that you are new to C++, that might be overkill).

In fact, the question you need to ask is, why do you want to store unrelated "types" in an "array" in the first place? and if they are related, then "how"? this will guide you in desgining a decent "Base_type" for the "types".

And finally, in short, C++ does not have homogenous array-like structures that can contain unrelated data types.

Comments

1

You could try to use an std::vector<boost::any> (documentation here).

1 Comment

Or boost::variant if the list is limited.

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.