Question

I have some vectors of class A objects:

 std::vector<A> *V1;
 std::vector<A> *V2;

etc

there is a function with a vector of pointers of A:

 std::vector<A *> *arranged;

what I need to do is put the vectors from V1, V2 etc inside arranged without destroying them in the end, so I thought that a vector of pointers to those objects... is this possible? if yes, can you give me an example of a iteration with variable V1 and add pointers of those objects into arranged?

imagine that you, temporarly, need to sort 3 vectors of objects into one vector but you don't want to mess up the memory of the 3 vectors.

ty,

Joe

Was it helpful?

Solution

You could write your own comparator. In this case, the comparator would work on A*. A simple example using int type:

void fun(vector<int*>* vec)
{
  /////////
}

bool comp(int* lhs, int* rhs)
{
    return *lhs < *rhs;
}

int main()
{
    vector<int> first, second;
    vector<int*> vec;

    for(vector<int>::size_type i = 0; i < first.size(); ++i)
        vec.push_back(&first[i]);
    for(vector<int>::size_type i = 0; i < second.size(); ++i)
        vec.push_back(&second[i]);

    // write your own comparator! provided above: comp
    sort(vec.begin(), vec.end(), comp);

    fun(&vec);

    return 0;
}

OTHER TIPS

If I understand you correctly - you've several vectors containing some object type (A), and you want to create a new vector containing the composition of all members of the other vectors w/o actually copying the objects around, or otherwise disturbing their owning-vectors in any way?

First: does the new composite vector's life definitely exist such that none of its source-vectors will change? That is: you cannot just have raw pointers into the source-vectors from your composite vector if those pointers will be invalidated within the lifetime of your composite.

If the answer to that is anything other than "definitely, pointers will remain valid" then you need to consider using shared pointers, or something similar, such that altering the source-vectors will not leave your composite vector in an invalid state (i.e. not leave it pointing to random memory).

Assuming that the source-vectors will remain unchanged in terms of their own contents for the life span of your composite, then the simple answer is "Yes"

vector<A> source1;
vector<A> source2;
vector<A> source3;

vector<const A*> composite; // this is a sorted vector of the above vectors' contents (by pointer)

For the composite vector, you would need to put the contents (by copy) of source1-3 into it, and then sort it (or you could use a sorted container, and sort as you insert the elements). You'll need to define your own sorting operator, one that dereferences the pointers and applies whatever sort-algorithm on the target objects themselves.

Does that help you?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top