push_back

Could someone explain me what does this funcion do. English isnt my native tongue, so it causes me some problems.

If this doesent do it, then what function add a character ata the begginning of string. So that character that once was on the position of 0 is now 1, and what was 1 is now 2 etc.
push_back() adds whatever data is within the parenthesis to the end of the vector, thereby increasing the size of the vector by 1. For example:

1
2
3
4
5
vector <int> test;
int myNumber;

cin >> myNumber;
test.push_back(myNumber);


would result in a vector that has one value - that value being whatever you set myNumber to be. Let's assume you entered 1. Your vector would now look like: {1}

If you asked for a different number and pushed that value back (let's say you entered 2), your vector would look like: {1,2}

If you want to put something at the beginning, check out:

http://www.cplusplus.com/reference/stl/vector/insert/

You can try a deque container http://www.cplusplus.com/reference/stl/deque/
it has methods push_back() and push_front(), and new value at the end and at the beginning of sequence.
Failing any of these you could do it the long way round by adding a value using push_back() and have a temparary variable and a for statement to move everything down by one field...
And if you want to asign anything to the first character its just vectorName[0] = assignment
The insert member function basically does all of the work that SatsumaBenji is describing, but automatically. Either way, it's definitely more taxing on the system as opposed to just putting a value in the back, but there are definitely reasons to want a value in the front. Doing it the manual way would be good practice though if you're a beginner.

Depending on what you're doing though, you could always just read the vector backwards, if all you're worried about is output. :)
so i need to create a vector. THen eachtim i want to add something to beginngin i use vector.insert(it, value). Can the value be int type, ot does it have to be char or string or whatever.
Can the value be int type, ot does it have to be char or string or whatever.

Depends on what your vector is. You can have a vector of ints, strings, chars, whatever.

1
2
3
4
5
6
7
// Basic syntax
vector<data_type> identifier;

// Example
vector<int> my_ints;
vector<char> my_chars;
vector<string> my_strings;
i need to make dec to binary converter. and well, the locaritm goes that lets say 18. 18%2 = 0 so the last number in binary must be 0. i want a string that contains these numbers, so each time i get a new 0 or 1 it is added to the begginning of the number.
Last edited on
> so each time i get a new 0 or 1 it is added to the begginning of the number.

Either
1
2
3
std::string str = "1011" ;
int number = 18%2 ;
str.insert( str.begin(), '0' + number ) ;


Or
1
2
3
std::string str = "1011" ;
int number = 18%2 ;
str = char( '0' + number ) + str ;
Topic archived. No new replies allowed.