PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] How to make pointer/reference on element in vector?

 July 10, 2022     c++, pointers, reference, vector     No comments   

Issue

I have two vectors and for some elements (not all) i need them to be connected ~ if i delete/change this element in one vector it should be removed/changed in both.

Something similar like pointers:

int r = 10;
int *p= &r;
*p = 3;

For example in next code it should change myvector2[0].a to 7.

#include <iostream>
#include <vector>

using namespace std;

struct elt {
    int a, b, c;
};

int main()
{

    vector<elt> myvector;
    vector <elt> myvector2;
    elt elt1 = {1,3,3};

    myvector.push_back(elt1);
    elt *elt2 = &elt1;
    myvector2.push_back(*elt2);

    myvector[0].a=7;

    cout << myvector[0].a << endl; //7
    cout << myvector2[0].a << endl; //1

    return 0;
}

How can i make this possible? Please help!!!


Solution

As tgmath explained, the issue is that you wind up with two different objects in your vectors, as the standard containers store elements by value. I would recommend that you use shared pointers to properly maintain the lifetime of the objects (note this uses C++11 features):

#include <iostream>
#include <vector>
#include <memory>

struct elt {
    int a, b, c;
};

int main()
{
    std::vector<std::shared_ptr<elt>> myvector;
    std::vector<std::shared_ptr<elt>> myvector2;
    auto elt1 = std::make_shared<elt>(elt {1,3,3});

    myvector.push_back(elt1);
    myvector2.push_back(elt1);

    myvector[0]->a=7;

    std::cout << myvector[0]->a << std::endl; //7
    std::cout << myvector2[0]->a << std::endl; //7

    return 0;
}


Answered By - Dark Falcon
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing