Vectors

Hi All,

I'm trying to insert an integer into my vector, but my teacher doesn't wont me to use the insert function. I've look for an alternative, but I keep finding tutorials on insert functions. Can anyone help me insert the integer 5 between element 4 and 5?

#include <iostream>
#include <vector>

using namespace std;

void printVector(vector<int> b)
{
for(int i = 0; i < b.size(); i++)
{
cout << b[i] << endl;
}

}

int main()
{

vector<int> myVector(5);

myVector[0] = 1;
myVector[1] = 2;
myVector[2] = 3;
myVector[3] = 4;
myVector[4] = 6;

printVector(myVector);

return 0;
}
Use the push_back method :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> vectorOfInt; // Creating the vector

	int x = 10;
	int y = 22;

	vectorOfInt.push_back(x); // Adding x to the vector.

	// Looping trough the vector to print elements value.
	for (int i = 0; i < vectorOfInt.size(); i++)
	{
		cout << vectorOfInt[i] << " ";
	}
	cout << endl;

	vectorOfInt.push_back(y); // Adding y to the vector.

	// Looping trough the vector to print elements value.
	for (int i = 0; i < vectorOfInt.size(); i++)
	{
		cout << vectorOfInt[i] << " ";
	}
	cout << endl;

	system("pause");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>

using namespace std;

void printVector(vector<int> b) {
    for (int i = 0; i < b.size (); i++) {
        cout << b[i] << endl;
    }

}

int main() {
    vector<int> myVector (5);
    myVector[0] = 1;
    myVector[1] = 2;
    myVector[2] = 3;
    myVector[3] = 4;
    myVector[4] = 6;
    
    // take the value "6" ->myVector[4] and push on to back of stack
    myVector.push_back (myVector[4]);
   // set myVector[4] to 5
    myVector[4] = 5;
    
    printVector (myVector);
    return 0;
}
Last edited on
Do you mean between myVector[3] and myVector[4]? you could
1
2
3
4
int temp;
temp = myVector[4];
myVector[4] = 5
myVector[5] = temp;  


Thank you, Viiarge, Bdanielz, and Nick. They help was much appreciated.

Cheers,

Mark
Topic archived. No new replies allowed.