0

i need to write a program in which main() would read a file(containing some predefined instructions) and create classes for each line and if a class object was already created, create a new class object.. something like

main()
{
     read file;
     save to a vector;

     for(i < vectorsize; i++)
          if(vector[i]== "book")
                 if(book b was already created) 
                       book c; 
                 else book b;
}
Prasanth Madhavan
  • 12,657
  • 15
  • 62
  • 94
  • Have you read [your good introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list)'s chapter on how to perform I/O? – James McNellis Nov 22 '10 at 06:44
  • What's the difference between `book b` and `book c`? What if you had to make 100 `book` instances based on the file contents? This wouldn't scale up very well and you probably want to add additional objects to a container (like, say, `std::vector`). – wkl Nov 22 '10 at 06:48
  • @biyyyree : thats what i had in mind.. but i want to update a book lateron how do i find it from the vector of a 100 booknames ASAP?? – Prasanth Madhavan Nov 22 '10 at 06:54

2 Answers2

1

Rather than having a vector you might want look at a std::map where you can have the book name be the key and the actual book be the value. That way you can find the book you're looking for very easily.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • I think the vector's meant to have captured the instructions read from file, which are then executed in sequence, so no need for a map. Not sure why they're not executed as they're read, avoiding the need for storage and iteration... :_/? But, as Rudi also points out - the books themselves can be in maps. – Tony Delroy Nov 22 '10 at 08:18
1

You might use a std::map to store the created books. A map is a key->value store where you can adress the content by a own defined key.

typedef std::map<std::string, Book> BookMap;
int main()
{
     read file;
     save to a vector;
     BookMap books;

     for(i < vectorsize; i++)
          if(vector[i]== "book")
                 BookMap::const_iterator alreadyCreatedBook(books.find(b.name));
                  // When there is no book in the map, the map returns it's end() element
                 if(books.end() != createdBook)
                       alreadyCreatedBook->second; 
                 else
                     books[b.name] = b;
}
Rudi
  • 19,366
  • 3
  • 55
  • 77