Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to store two data types in a vector

I need to store two values width different data types in a vector, example:

vector<HWND, long> hwnd;

And then get by index and access to the two values:

hwnd[0] // Get HWND and long
hwnd[1] // Get HWND and long

Is it correct to ask for a vector solution to this or maybe use a hashmap solution? I haven't used hashmap yet that's why I'm wondering this. Thanks in advance.

like image 553
ProtectedVoid Avatar asked Mar 22 '26 00:03

ProtectedVoid


1 Answers

While using a std::pair is a correct solution, it loses some clarity because you would access the elements like this:

hwnd[0].first
hwnd[0].second

which makes it absolutely not clear which is a handle and which is a long.

You should instead use a struct (I'm using count here as an example of use case, your own long might have an entirely different meaning):

struct HandleCount {
    HWND handle;
    long count;
};

So your code would look like:

std::vector<HandleCount> hwnd;

hwnd[0].handle
hwnd[0].count

So, while you lose a little bit of simplicity by using a supplementary type, you instead benefit in simplicity of understanding the code.

like image 191
SirDarius Avatar answered Mar 24 '26 12:03

SirDarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!