Resizing Vector of shared pointers

J

joe

Brain Block.

I thought there was a way to do this in less lines (1 line?):

std::vector<boost::shared_ptr<T> > m_vec;

for (int i =0; i<totalSize; ++i)
{
m_vec.push_back(new T);
}

but my brain isn't letting me remember how right now. Anyone out
there want to help?

Joe C
 
A

acehreli

I thought there was a way to do this in less lines (1 line?):

std::vector<boost::shared_ptr<T> > m_vec;

for (int i =0; i<totalSize; ++i)
{
   m_vec.push_back(new T);

}

m_vec.resize(totalSize);

Ali
 
T

Thomas J. Gritzan

m_vec.resize(totalSize);

This will fill the vector with empty shared_ptr, while the above loop
will fill the vector with allocated objects. So they won't do the same.
 
B

Bo Persson

joe said:
Brain Block.

I thought there was a way to do this in less lines (1 line?):

std::vector<boost::shared_ptr<T> > m_vec;

for (int i =0; i<totalSize; ++i)
{
m_vec.push_back(new T);
}

but my brain isn't letting me remember how right now. Anyone out
there want to help?

It depends somewhat on T, and what you are doing with it. If you
want/need to have a certain number of distinct Ts, you just need to
use 'new' that number of times. If it is ok to share a single T, you
can do that in the constructor.


Bo Persson
 
J

joseph cook

It depends somewhat on T, and what you are doing with it. If you
want/need to have a certain number of distinct Ts, you just need to
use 'new' that number of times. If it is ok to share a single T, you
can do that in the constructor.

Bo Persson

Oh, well, I thought somehow I could create distinct T's in a
constructor line...I must have had too much pumpkin wine.

Joe C
 
S

Stephen Horne

std::vector<boost::shared_ptr<T> > m_vec;

for (int i =0; i<totalSize; ++i)
{
m_vec.push_back(new T);
}

but my brain isn't letting me remember how right now. Anyone out
there want to help?

I can do the loop in one line, but you won't like it...

while (m_vec.size () < totalSize) m_vec.push_back (new T);

I said you wouldn't like it ;-)
 
J

James Kanze

I thought there was a way to do this in less lines (1 line?):
std::vector<boost::shared_ptr<T> > m_vec;
for (int i =0; i<totalSize; ++i)
{
m_vec.push_back(new T);
}
but my brain isn't letting me remember how right now. Anyone
out there want to help?

How about std::fill_n with a back inserter and a
boost::function_output_iterator. For that matter, I'm pretty
sure that I saw an iterator adapter somewhere which stopped
after a maximum of n times; use that with the
function_output_iterator, and you should be able to use the two
iterator form of the constructor directly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top