Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- // Lagrar: namn och ålder
- class Person{
- public:
- string name;
- int age;
- Person(string _name, int _age);
- void setAttribute(string _name, int _age);
- void print ();
- };
- //konstruktor
- Person::Person(string _name, int _age){
- name = _name;
- age = _age;
- }
- //Byta namn, ålder
- void Person::setAttribute(string _name, int _age){
- name = _name;
- age = _age;
- }
- //Metod för att printa ut namn och ålder.
- void Person::print(){
- cout << name << " : " << age << endl;
- }
- //funktion för att lägga till nya familjemedlemmar
- void add (int &antal, vector<Person> &familj){
- string tName; // temporary name
- int tAge; // Temporary age
- cout << "\nHow many family members do you want to add? --> ";
- cin >> antal; cout << endl;
- for (int i=0; i < antal; i++){
- cout << "Enter name: "; cin >> tName;
- cout << "Age of " << tName << ": "; cin >> tAge; cout << endl << endl;
- familj.push_back(Person(tName, tAge)); // lägger till sist i listan och för över värden från tName, tAge till Person name; age;
- }
- }
- int linearSearch(int &antal, vector<Person> &familj, int &key){
- cout << "Which age are you looking for? --> ";
- cin >> key;
- for (int i=0; i<antal; i++){
- if (familj[i].age == key){
- return i;
- }
- return -1;
- }
- }
- int main(int argc, char** argv) {
- string choice1;
- int antal = 0;
- vector<Person> familj;
- do{
- cout << "[A]dd family\n[P]rint family members\n[L]inear search\n[S]ort\n[B]inary search\n[Q]uit\n--> ";
- cin >> choice1;
- if (choice1 == "a" || choice1 == "A"){
- add(antal, familj);
- system("PAUSE");
- system ("cls");
- }
- else if (choice1 == "p" || choice1 == "P"){
- cout << endl;
- for (int i = 0; i < antal; i++){ // tyckte detta var en rätt smart lösning :P Innan hade jag for-loopen inuti print
- familj[i].print();
- }
- system("PAUSE");
- system ("cls");
- }
- else if (choice1 == "l" || choice1 == "L"){
- int key;
- cout << endl;
- int index = linearSearch(antal, familj, key);
- if (index == -1){
- cout << "Could not find person\n";
- }
- else {
- cout << "Name of family member with age " << key << ": " << familj[index].name << "\nIndex number: " << index << endl;
- }
- system("PAUSE");
- system ("cls");
- }
- }
- while (true);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment