0

I need to push some elements into an existing vector as I assign them to an array.

I am able to initialize them and then further copy them, but I need to do both the operations at once.

Say there is a Base class TestBase and derived class TestOne, TestTwo, TestThree. I have initialized them based on the type using an enum as shown. I do have an existing vector which I want to push these items into.

enum class Type : std::uint8_t {
TYPE_ONE,
TYPE_TWO,
TYPE_THREE
}; //enum class Type

struct _ds {
enum class Type type;
std::shared_ptr<TestBase> p_str;
};

std::vector<std::shared_ptr<TestBase>> vec_base_ptrs;

int main(int argc, char *argv[]) {
_ds a_ds[] = {{Type::TYPE_ONE,std::make_shared<TestOne>()},
          {Type::TYPE_TWO,std::make_shared<TestTwo>()},
          {Type::TYPE_THREE,std::make_shared<TestThree>()}};
}

Now is there a possibility, where I can do the following, where I can push the pointers into vector as well as have it in array at the same it. Is it possible.

    _ds a_ds[] = {{Type::TYPE_ONE,{vec_base_ptrs.push_back(std::make_shared<TestOne>())}},
               {Type::TYPE_TWO,{vec_base_ptrs.push_back(std::make_shared<TestTwo>())}},
               {Type::TYPE_THREE,{vec_base_ptrs.push_back(std::make_shared<TestThree>())}}};

Please let me know how to do it. Also suggest if there are any other data structures that can help in solve this problem, with a note that I need to fill the vectors with the shared_ptrs as I am getting it from third party library.

TechTotie
  • 127
  • 1
  • 15
  • 1
    *but I need to do both the operations at once.* Why? The way to do this is not not do them together. There isn't any magic performance benefit doing it together. It could actually be harmful – NathanOliver Sep 27 '19 at 13:42
  • Also be very careful using leading underscores. It' best to avoid them. See: https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – NathanOliver Sep 27 '19 at 13:44

0 Answers0