Hi all - hope you can help me with this.
I'm trying to search through a vector of struct's; I'm able to loop through the vector using a simple for() loop, but i'm unable to use the generic find(). Secondly i want to delete a element
if there's a match.
Below is what I have so far (sorry about the big chunk of code, but i'm a newbie so my problem might be how the vector is passed or something - hence the whole code)
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // For find
using namespace std;
struct Person
{
std::string Name;
std::string Address;
int Phone;
};
void ChangeAdr(string Name, string Adr, vector<Person>& Book);
void Delete(string Name, vector<Person>& Book);
int main(int argc, char *argv[])
{
vector<Person> Book;
string Name, Adr;
// Add contact
Person x;
x.Name = "James";
x.Address = "Bond";
x.Phone = 007;
Book.push_back(x);
// Edit address
cout << "Enter contacts name: ";
getline(cin, Name);
cout << "Enter new address: " ;
getline(cin, Adr);
ChangeAdr(Name, Adr, Book);
//Delete Contact
cout << "Enter contacts name: ";
getline(cin, Name);
Delete(Name, Book);
return 0;
}
void ChangeAdr(string Name, string Adr, vector<Person>& Book)
{
for (int i=0; i!=Book.size(); i++)
{
if (Book[i].Name == Name)
{
Book[i].Address = Adr;
break;
}
}
}
void Delete(string Name, vector<Person>& Book)
{
for(vector<Person>::iterator j = Book.begin(); j != Book.end(); ++j)
{
if ((*j).Name == Name)
{
delete (*j); // Dosn't work !
break;
}
}
}
The changeAdr() works fine, but i don't understand why i can't use find()
eg.
vector<Person>::iterator where = find(Book.begin(), Book.end(), Name);
(*where).Address = Adr;
Regarding delete (*j) the compiler gives the following error:
"main.cpp type `struct Person' argument given to `delete', expected pointer"
Thx in advance
Kind Regards Dan