Last active
May 19, 2018 21:16
-
-
Save scriptpapi/519dd5be8c7c46cc6872a14153c2ffcb to your computer and use it in GitHub Desktop.
a simple C++ vector implementation with some applications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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