-5

I have to create a vector containing selected elements of another vector. Changes made in one vector should reflect in the other vector too. So I have to use reference of the elements which I intend to copy.

For example,

std::vector<int> a{1,2,3,4,5,6};
std::vector<int> b;

Suppose if I copy odd numbers with reference to b vector, b will contain 1,3 and 5. If I change the values of b, same changes should be seen in a vector also.

What it the method in STL to do this?

EDIT:
I was in assumption that same memory address location can be shared by more than one variables.
The purpose of the above code was, to pass smaller vector of unknown variables, to an external solver to be solved. Since changes will be automatically updated in the larger vector, I don't need to keep track of it. It seems I have to use pointers for the above purpose.

hisham
  • 215
  • 1
  • 9
  • 6
    This is dangerous. A `std::vector` may re-allocate its internal buffer when new elements are added. Thus, `b` will lose its references. Btw. I once answered a similar question: [vector of existing objests](https://stackoverflow.com/questions/42039110/vector-of-existing-objests/42039844#42039844). (It uses `std::reference_wrapper` as proposed by user2079303.) – Scheff's Cat Jun 12 '17 at 12:25
  • why do you need a second vector in the first place? If you want to modify all odd entries of `a`, then its much easier to simply modify the odd entries in `a` – 463035818_is_not_an_ai Jun 12 '17 at 13:03
  • @tobi303, in my program larger vector is unsolved variables and I will pass some of its elements (smaller vector) to an external library to solve those variables. – hisham Jun 12 '17 at 14:30

1 Answers1

3

If I change the values of b, same changes should be seen in a vector also.

Then b should not contain integers, but references. Therefore the template type argument is wrong. You want references, not integers.

However, references cannot be stored in containers. The workaround is simple: You can use std::reference_wrapper cases like this are what the wrapper is meant for. You could alternatively use a pointer, but pointers can be null which you may want to avoid.

Do remember to pay attention to documentation of vector. In particular to reference invalidation rules which are very relevant here.

eerorika
  • 232,697
  • 12
  • 197
  • 326