Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Last active May 19, 2018 21:16
Show Gist options
  • Save scriptpapi/519dd5be8c7c46cc6872a14153c2ffcb to your computer and use it in GitHub Desktop.
Save scriptpapi/519dd5be8c7c46cc6872a14153c2ffcb to your computer and use it in GitHub Desktop.
a simple C++ vector implementation with some applications
//A Simple implementation of vector(containing objects of a class) data structure
#include <iostream>
#include <vector>
using namespace std;
class Salad{
private:
int oranges, apples;
public:
void setOranges(int numOranges){ oranges = numOranges; }
void setApples(int numApples){ apples = numApples; }
int getOranges(){ return oranges; }
int getApples(){ return apples; }
};
int main(){
//Instantiating a vector
int numSalad = 7; //vector size variable
std::vector<Salad> saladVector;
saladVector.resize(numSalad);
//Performing set operations on vector elements
for(int i = 0; i < numSalad; i++){
saladVector[i].setApples(numSalad - i);
saladVector[i].setOranges(0 + i);
}
//Performing print operations on vector elements
for(int i = 0; i < numSalad; i++){
cout << "Apples:" << saladVector[i].getApples() << " Oranges:" << saladVector[i].getOranges() << endl;
}
//Delete a random element from the vector
int numDel = rand() % numSalad + 0;
saladVector.erase(saladVector.begin()+numDel);
//Printing vector size
cout << "size: " << saladVector.size() << endl;
//Delete the last 2 elements
saladVector.erase(saladVector.end(), saladVector.end()-2);
//Printing vector size
cout << "size: " << saladVector.size() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment