0

I want to add an element to a C++ STL vector and then return its address. Perhaps that is not "safe" or possible? If it is a reasonable thing to do, I am not having any luck.

struct myStruct{...};

myStruct *myMethod() {
    myStruct myS(...);
    myVector.push_back(myS);
    // I cannot get the following line or any variant thereof to compile
    myStruct *foo = myVector.rebegin();  // or .rend()-1; or &myVector.rebegin();   
    return foo; }

As I say, is what I want to do illogical or illegal, and if not, how do I do it? I don't want to use the address of myS because it is on the stack, and I can't make it static because I re-parametize it each time through the method.

Thanks, Charles

Charles
  • 479
  • 1
  • 3
  • 13
  • 1
    What is the scope of `myVector`? And what do you have against `vector::iterator`? – Beta Dec 24 '20 at 00:28
  • @JaMiT's link I think answers my question. I think perhaps I don't want to/"can't" do this because additions to the vector may move things around, so an address could become invalid unpredictably. Agree? Disagree? – Charles Dec 24 '20 at 00:35
  • @Beta myVector is at the class level and I have nothing against anything. Doesn't rbegin() for example return a vector::iterator? – Charles Dec 24 '20 at 00:37
  • I think I need to re-do the vector as <* myStruct>, allocate a new element, and delete it at end-of-run. – Charles Dec 24 '20 at 00:38
  • A copy of the struct in the vector will not do the job -- the caller of the method wants to modify an element of the struct. – Charles Dec 24 '20 at 00:39
  • 1
    Just because you can doesn't mean you should. If your design requires this then you should probably take a hard look at that and consider revising it. You haven't really said why you need this so I wonder if we're looking at an XY problem. – Retired Ninja Dec 24 '20 at 00:42
  • Addresses of elements can be invalidated by additions to the vector. And `rbegin()` returns `reverse_iterator`, which is not quite the same as `iterator`. If you want iterators that remain valid after additions, you might consider `list` instead of `vector`. – Beta Dec 24 '20 at 00:50
  • @Beta got it, thanks. – Charles Dec 24 '20 at 01:16

2 Answers2

1

You want return &myVector.back();.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

std::vector in C++11 and later have member function named "data()", which does the thing you want

https://en.cppreference.com/w/cpp/container/vector/data

s.b.
  • 96
  • 1