I have two vector objects that contain different types of data that are ordered in the same way. My situation looks something like this:
struct Info
{
double opaque_data_not_relevant_to_this_problem[6];
int data_len;
bool operator<(const Info &rhs) const
{
return (bool) irrelevant_operation_on_opaque_data;
}
};
vector<Info> vec1;
vector<double> vec2;
For each Info entry in vec1, vec2 contains a sequence of double values, equal in length to the value of data_len in the corresponding element in vec1. For example:
vec1[0].data_len == 100 ==> vec2[0:99] correspond to vec1[0]
vec1[1].data_len == 150 ==> vec2[100:249] correspond to vec1[1]
// and so on
I understand that this arrangement is not very OO and there is probably a “more C++” way to do this. However, other constraints in my environment force me toward this type of data packing, so I need to work around it. Unfortunately, the length of each data record in vec2 (specified by its data_len counterpart in vec1) are not known until runtime, and the length varies from record to record.
My problem: I would like to sort the two vectors by some criteria. Sorting vec1 is simple, as I can just use std::sort. At the same time, however, I need to sort vec2 such that the ordering described above is still maintained (i.e. the first block of values in vec2 corresponds to vec1[0] after it is sorted). It would be nice if I could get some kind of “index vector” out of the sorting process that I could then use to reorder vec2 (in-place or out-of-place operation would be fine), but I’m not sure of a good way to do that with the standard library (if there is one).
I could do the sort by defining a second intermediate structure that bundles the two together:
struct SortableInfo
{
Info info;
vector<double> data;
bool operator<(const SortabelInfo &rhs) const { return info < rhs.info; }
};
vector<SortableInfo> vec3;
I would then populate vec3 appropriately based on the contents of vec1 and vec2, sort it, then fan the data back out to separate vectors again. However, this doesn’t seem particularly efficient. Any suggestions on a better way to execute this?
You could store in your
SortableInfopointers to the start positions in the correspondingvec2populate your
vec3, sort it and then at the end make an ordered copy of yourvec2using the sorted pointers.