views:

93

answers:

2

In C++ I have 2 STL vectors A and V. A has data and is able to change it, V only points to data but reads only and can't modify it. So if these two vectors are inside a class what will be the syntax of

  1. Variables definition
  2. assigning A reference into V
  3. get_A() and get_V() will it return a reference or a pointer?

Also If I have other normal vectors like A, B, C, and D am I able to "insert" their references into V so that V can see them all one by one? For clearance V.size() will be equal to A.size() + B.size() + C.size().


Sorry for confusion,I think I've asked the question in wrong way

A: 

I believe what you are describing is something like a const alias for the data vector. What I am saying is that you need to work with a const reference to vector A.

An example (completely out of the blue, but describes my suggestion and understanding of the situation quite well):

class someClass
{
public:
    const std::vector & V() const
    {
        return A;
    }
private:
    std::vector<int> A;
};

From what I get from constness, this "protects" A through showing only the const version when someone "accesses" the vector through someClass::V().

rubenvb
+1  A: 
  1. The vectors will be declared as

    vector<Data> A;
    vector<const Data *> V;
    

    (Note that V cannot be a vector of const Data & because references are not Assignable, and vector requires an Assignable template type.)

  2. Assigning a reference from A into V would look like this:

    V[i] = &A[i];
    
  3. I'm not sure what you mean by get_A and get_V. My best guess is that you are referring to what the results of operator[] on A and V are. A[i] returns a reference to a Data, that is a Data&. V[i] technically returns a reference to a const Data pointer, i.e. const Data * &, but effectively you would use it as a pointer, i.e. a const Data *.

Regarding the question about A, B, and C: if they are the all vectors of same type, and they do not change size, you could set up V to contain pointers to the elements in each one of them. But if they do change size, then appending an element to, say, A, after having set V up would mean you would have to insert the pointer to the new element of A into the correct offset of V, which is possible but seems like a hassle.

A quick example of setting up such a V would look like this:

vector<Data const *> V;
for (size_t i = 0; i < A.size(); ++i) { V.push_back(&A[i]); }
for (size_t i = 0; i < B.size(); ++i) { V.push_back(&B[i]); }
for (size_t i = 0; i < C.size(); ++i) { V.push_back(&C[i]); }
SCFrench
yep that's what i'm looking for thanks mate
ismail marmoush