maccame
maccame

Reputation: 45

vectors and structures C++

I have a text file,

cat molly
dog benji
bird charlie (etc..)

in another text file, "one day cat went out to lie in the sun - dog was already in the garden..." (etc..)

I am supposed to replace the animal with it's name. At the moment I am reading in the file and placing the animal type in one vector and the animal name in another vector. My question is - do I need to put them in a structure so that when I loop through and find cat I can find the associated name - or do I use another method. I've heard of multidimensional vectors but feel it may be over my head as I am very new to programming.

Upvotes: 1

Views: 139

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

It seems that the most appropriate structure for you to use would be a map. It would allow you to associate an animal with a name and easily and efficiently look up the animal's name.

Try this:

std::map<std::string, std::string> animal_names;

The first template type is the key type and the second one is the value type. In your case, the keys are animals and the values are names.

You can then insert associations with this:

animal_names["cat"] = "molly";

Very simple! Note that if you now iterate over the map, you will get them in order of animal. That is "bird" will come first, then "cat", then "dog".

If you don't care about the order at all, you can instead use an std::unordered_map. This will improve the access and insertion time.


Since you say you are a beginner, I'll give you an example of how I would read your file:

std::ifstream file("animal_names.txt");
std::string animal, name;
std::map<std::string, std::string> animal_names;

while (file >> animal >> name) {
  animal_names[animal] = name;
}

Later, if you want to print out, for example, the name of the cat, just do:

std::cout << animal_names["cat"] << std::endl;

Upvotes: 3

LihO
LihO

Reputation: 42133

To map types of animals to their names, you want to use std::map<std::string, std::string>, where the key will be animal and the value will be its name, example:

std::map<std::string, std::string> animalNames;
animalNames["cat"] = "molly";

Then later when youw ill iterate through std::vector<std::string> you will just check if the word you are currently iterating through does exist as a key in your map and replace it with its value.

Upvotes: 2

Related Questions