user1290126
user1290126

Reputation: 53

How to add elements to container having only iterator?

I have an empty container with reserved memory. My function (algorithm) doesn't take a container, only the iterator to begin of it. How to add elements to container in this function? I need allocate memory and call the constructor, but how to call the constructor in place referenced by iterator?

Upvotes: 1

Views: 1733

Answers (4)

D_E
D_E

Reputation: 1206

You cant change container, having only traverse iterator; however, you can use insert iterator instead.

Edited: If you reserve memory you must know how many elements it will contain. Then you can add empty elements before passing into the function instead and fill them using the iterator, incrementing it. After that you can return this iterator and it will point to the position where usefull data end.

Upvotes: 3

Ben Cottrell
Ben Cottrell

Reputation: 6130

C++ has the concept of an insert_iterator, which is what I assume you're after?

for example:

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    int my_array[] = { 1,2,3,4,5,6,7,8,9,10 };
    std::vector<int> my_vector;

    std::copy( std::begin( my_array ),
               std::end( my_array ),
               std::back_inserter( my_vector ) );
}

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490663

Normally by using something like an std::inserter_iterator. This, however, doesn't normally eliminate the requirement for a pointer or reference to the container -- it just stores that reference inside the iterator itself.

If you have a pre-set iterator type, this does no good. If you have something like a normal algorithm that just needs to take and use something that uses an iterator interface to insert into the collection, it works beautifully.

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272772

You can't insert an element into a container without a reference/pointer to that container.

You can, however, overwrite an element (assuming you don't have a const_iterator). Something like:

*it = T(params);

where T is the type in question.

Upvotes: 2

Related Questions