It compiles and runs, but after "Here is the starting empty cubes vector" prints, I get this message:
Debug Assertion Failed!
Expression: vector subscript out of range
Can someone help me, please?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
// Cubed integers
class cubes
{
int cube; // The vector position cubed
public:
// Constructors
cubes () {cube = -1;}
cubes (int c) {cube = c * c * c;}
int get_cube () {return cube;}
};
// Overloaded operators
bool operator< (cubes a, cubes b) {return a.get_cube() < b.get_cube();}
bool operator==(cubes a, cubes b) {return a.get_cube() == b.get_cube();}
void show_vector (vector<cubes> &v);
// Show the vector specifications and contents
int main()
{
vector<cubes> v; // A vector
vector<cubes>::iterator p_v; // An iterator
vector<cubes>::reverse_iterator rp_v; // A reverse iterator
unsigned int i; // Counter variable
// Show the specs and contents of the starting vector
cout << "\n\nHere is the starting empty cubes vector:";
show_vector(v);
// Add 6 cubes and show the vector
cout << "\n\nAdding the first 6 cubes to the vector:";
for(i = 0; i < 6; i++)
v.push_back(cubes(i));
show_vector(v);
// Delete even cubes and show the vector
cout << "\n\nDeleting the even cubes from the vector:";
p_v = v.begin();
for(i = 0; i < (int) v.size(); i++)
{
v.erase(p_v + i);
p_v++;
}
show_vector(v);
// Reinsert the even cubes and show the vector
cout << "\n\nInserting the even cubes back into the vector:";
p_v = v.begin();
for(i = 0; i < (int) v.size(); i += 2)
v.insert(p_v + i, v[i].get_cube());
show_vector(v);
// Add 4 cubes and show the vector
cout << "\n\nAdding the next 4 cubes to the end of the vector:";
p_v = v.end();
for(i = 6; i <= 9; i++)
{
v.insert(p_v, v[i].get_cube());
p_v++;
}
show_vector(v);
// Add 4 empty cubes and show the vector
cout << "\n\nAdding 4 empty cubes to the end of the vector:";
for(i = 10; i <= 13; i++)
v.push_back(cubes());
show_vector(v);
// Remove the empty cubes and show the vector
cout << "\n\nRemoving the last 4 empty cubes from the vector:";
for(i = 1; i <= 4; i++)
v.pop_back();
show_vector(v);
// Show the vector contents in forward and reverse order
cout << "\n\nPrinting the cubes with an iterator, then with a "
<< "reverse iterator:";
for(p_v = v.begin(); p_v <= v.end(); p_v++)
cout << "\n " << p_v->get_cube() << " ";
for(rp_v = v.rbegin(); rp_v <= v.rend(); rp_v++)
cout << "\n " << rp_v->get_cube() << " ";
// Clear the vector
cout << "\n\nRemoving all cubes from the vector:";
v.clear();
show_vector(v);
return 0;
}
void show_vector(vector<cubes> &v)
{
unsigned int i, // Counter variable
sum = 0; // The sum of the vector contents
for(i = 0; i <= (int) v.size(); i++)
sum += v[i].get_cube();
cout << " Size: " << (int) v.size()
<< " - Sum: " << sum
<< " - Capacity: " << v.capacity()
<< " - Max Size: " << v.max_size();
cout << " Cubes Vector contents: ";
for(i = 0; i <= (int) v.size(); i++)
cout << v[i].get_cube();
return;
}