Inserting an element in a 2-D vector

R

Raj

I have a 2-D vector declared as vector<vector <uint> > solution(m,
vector<uint>n). I have initialized this vector with values. Now I want
to insert an element in the (i,j) position. I am trying to do
solution.insert(j, 1, value), but this gives me the error 'no
matching function for call to 'std::vector<unsigned int,
std::allocator<unsigned int> >::insert(uint&, int, int)'

How do I get this done?

Thanks,
Raj
 
T

tonydee

I have a 2-D vector declared as vector<vector <uint> > solution(m,
vector<uint>n). I have initialized this vector with values. Now I want
to insert an element in the (i,j) position. I am trying to do
solution.insert(j, 1, value), but this gives me the error 'no
matching function for call to 'std::vector<unsigned int,
std::allocator<unsigned int> >::insert(uint&, int, int)'

How do I get this done?

Thanks,
Raj


Given
iterator insert(iterator pos, const T& x)

Try
solution.insert(solution.begin() + j, value)

I trust you realise, in psuedo-code:
{1, 2, 4}.insert(begin() + 2, 3) == {1, 2, 3, 4}
whereas
{1, 2, 4}[2] = 3 == {1, 2, 3}.
The former is typically slower, as elements after the insertion point
need to be "moved over" to make space, and sometimes the array may
need to be resized and all elements copied. Only if this proves a
performance problem with your particular data set, you may want to
consider using a std::list<>....

Cheers,
Tony
 
R

Raj

Thanks for the answer. It works now!

Raj
I have a 2-D vector declared as vector<vector <uint> > solution(m,
vector<uint>n). I have initialized this vector with values. Now I want
to insert an element in the (i,j) position. I am trying to do
solution.insert(j, 1, value), but this gives me the error 'no
matching function for call to 'std::vector<unsigned int,
std::allocator<unsigned int> >::insert(uint&, int, int)'

How do I get this done?
Thanks,
Raj

Given
    iterator insert(iterator pos, const T& x)

Try
    solution.insert(solution.begin() + j, value)

I trust you realise, in psuedo-code:
     {1, 2, 4}.insert(begin() + 2, 3) == {1, 2, 3, 4}
whereas
     {1, 2, 4}[2] = 3 == {1, 2, 3}.
The former is typically slower, as elements after the insertion point
need to be "moved over" to make space, and sometimes the array may
need to be resized and all elements copied.  Only if this proves a
performance problem with your particular data set, you may want to
consider using a std::list<>....

Cheers,
Tony
 

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,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top