0

I have below code

PositionSummary** psArray_= new PositionSummary*[instSize]
for (int k = 0; k < instSize_; k++)
{
    PositionSummary* ps = new PositionSummary();
    psArray_[k] = ps;

}

when I try to do a copy as below, it doesn't work out

std::copy(begin(psArray_),end(psArray_),std::back_inserter(psContainer_));

Compiler reports "no matching function for call to ‘begin(PositionSummary*&)", how to get around this?

2
  • std::copy(begin(psArray_),end(psArray_),std::back_inserter(psContainer_));___ it is here ah...I missed a "*" here, and I added now... Commented Feb 15, 2015 at 7:51
  • It should be std::begin and std::end unless you have overloads for begin and end that will be found by ADL. Commented Feb 15, 2015 at 7:55

2 Answers 2

1

That doesn't work because psArray_ is not an array at all, it is a pointer. You may know that it points to an array of a specific size, but the compiler has no (general) way of knowing this. If you were to make it an array it would work fine. Try to declare psArray_ like this:

PositionSummary* psArray_ [instSize];

This will work, but presumably not for you because I'm guessing instSize is not a compile time constant. You can fix that by using a vector instead of doing your own memory allocation:

std::vector<PositionSummary*> psArray_;
for (int k = 0; k < instSize; k++) 
    psArray_.push_back (new PositionSummary());

std::copy(psArray_.begin()),psArray_.end(),std::back_inserter(psContainer_));

For further improvement, you could consider using a smartpointer in the vector (so you don't have to worry about freeing later). And while I have no idea of the greater context of your code, I'm still wondering why the copy is necessary at all - why not just construct your vector directly in the data structure that is ultimately supposed to hold it?

Sign up to request clarification or add additional context in comments.

Comments

1

psArray is just a pointer. std::begin and std::end cannot possibly know the length of the array the pointer points to. They work for plain arrays, not for pointers to arrays.

You can do this instead:

std::copy(psArray_, psArray_ + instSize, std::back_inserter(psContainer_));

assuming psContainer_ is a container holding pointers to PositionSummary.

Depending on the details of your application, you may be better off using an std::vector, either of smart pointers or values:

std::vector<some_smart_pointer<PositionSummary>> psArray_;

or

std::vector<PositionSummary> psArray_;

where the second option may be the better one if you don't need referential semantics.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.