guys my vector isn't working properly with push back function ... so i am searching for the alternative method ... please help me with your advices...

actually .. i just want to increase my knowledge .. for in case my program fails with push back so....

You can use resize() when you originally create the vector so that it will contain room for using [] to insert items

vector<int> ay;
ay.resize(10);
for(int i = 0; i < 10; i++)
   ay[i] = i;

or you can use an iterator

int main()
{
    int count = 0;
    std::vector<int> ay;
    ay.resize(10);
    std::vector<int>::iterator it;
    for(it = ay.begin(); it != ay.end(); it++)
        *it = count++;
}

Edited 6 Years Ago by Ancient Dragon: n/a

Aside from what AD proposed, there are all the modifiers in the std::vector class:
- assign() : overwrite the content of the vector from either a constant or another iterator pair (begin,end).
- push_back() : add an element at the end.
- pop_back() : subtract the last element.
- insert() : add an element or many elements just before a particular position.
- erase() : erase an element or many elements.
- swap() : swap the content of one vector with another.
- clear() : erase all the elements.

There are also a plethora of possibilities under the <algorithm> header. Many of these can be even more useful in combination with the back_inserter for example.

This article has been dead for over six months. Start a new discussion instead.