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...

6 Years
Discussion Span
Last Post by mike_2000_17

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;
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;
    std::vector<int>::iterator it;
    for(it = ay.begin(); it != ay.end(); it++)
        *it = count++;

Edited 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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.