Question

I need help defining a class in C++ that acts like a python dictionary. I need...

I need help defining a class in C++ that acts like a python dictionary. I need to be able to add keys-values to an already existing dictionary. For example

id= {'sam':75, 'robert':09907, 'timmmy',95453, 'samuel',5333)}.

i want to create a class in which i can do

id.add("samuel', 8439922) and it adds it to the dictionary. i want to implement this with using vectors to store the pairs.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey, the best way to achieve this would be using an unordered_map that maps a string to a key. In the case strings not unique and the keys are, you can do the other way around. However since you have asked for it to be done using vectors to store the pairs, here is how you can achieve it using vectors.

Code:

#include <bits/stdc++.h>
using namespace std;

class Dictionary {
   private:
   vector<pair<string, int>> dict;
  
   public:
   // Initialize an empty dictionary
   Dictionary() {
       dict.clear();
   }
  
   // Add a pair to the dictionary
   void add(string name, int key) {
      pair<string, int> p = {name, key};
      // Push the new dictionary entry into the vector
      dict.push_back(p);
   }
     
   // Function to print dictionary
   void printDictionary() {
      int len = dict.size();
      for(int i = 0; i < len; i++) {
          cout << "Name -> " << dict[i].first << ", Key -> " << dict[i].second << endl;
      }
   }
};

int main() {
   Dictionary d;
   d.add("Samuel", 123);
   d.add("John", 7868);
   d.printDictionary();
   return 0;
}

Sample output:

Add a comment
Know the answer?
Add Answer to:
I need help defining a class in C++ that acts like a python dictionary. I need...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help defining a class in C++ that acts like a python dictionary. I need...

    I need help defining a class in C++ that acts like a python dictionary. I need to be able to add keys-values to an already existing dictionary. For example id= {'sam':75, 'robert':09907, 'timmmy',95453, 'samuel',5333)}. i want to create a class in which i can do id.add("samuel', 8439922) and it adds it to the dictionary. i want to implement this with using vectors to store the pairs. I need to do this without using any features like maps, every thing has...

  • How to add class objects to a dictionary? *PYTHON ONLY* NO IMPORT RANDOM Write a class...

    How to add class objects to a dictionary? *PYTHON ONLY* NO IMPORT RANDOM Write a class named Employee that has data members for an employee's name, ID_number, salary, and email_address (you must use those names - don't make them private). Write a function named make_employee_dict (outside of the Employee class) that takes as parameters a list of names, a list of ID numbers, a list of salaries and a list of email addresses. The function should take the first value...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • I need help writing these : Given a dictionary gradeCounts = { "A": 8, "D": 3,...

    I need help writing these : Given a dictionary gradeCounts = { "A": 8, "D": 3, "B": 15, "F": 2, "C": 6} write the Python statement(s) to print: a. all the keys. b. all the values. c. all the key and value pairs. d. all of the key and value pairs in key order. e. the average value. f. a chart similar to the following in which each row contains a key followed by a number of asterisks equal to...

  • Using Python. Please help! The output should looks like below. Please follow the emphasis. I think...

    Using Python. Please help! The output should looks like below. Please follow the emphasis. I think it just prompt user to input course name. Write a modular program that creates a dictionary containing course numbers and the room numbers of the rooms where the courses meet. The dictionary should have the following key- value pairs: Course Number (key) Room Number (value) CS101 3004 CS102 4501 CS103 6755 NT110 1244 CM241 1411 The program should also create a dictionary containing course...

  • INTRODUCTORY PYTHON QUESTION For my Intro to Python class, I need a very simple program that...

    INTRODUCTORY PYTHON QUESTION For my Intro to Python class, I need a very simple program that generates random sentences using a dictionary / list and the random.choice function. The program must ask user how many sentences they want generated. The dictionary can look like this, just not sure where to go from here: words = [["The", "A"], ["young", "energetic", "happy", "small", "cute"], ["boy", "dog", "cat", "girl", "student", "child"], ["ate the homework.", "played with the ball.", "jumped on the desk.", "ate...

  • Hi, I need help with Python Dictionaries please. Question: Write a function named "add_key_value" that takes...

    Hi, I need help with Python Dictionaries please. Question: Write a function named "add_key_value" that takes a key-value store as a parameter with strings as keys and integers as values. The function will add a key-value pair to the input store with a key of "slam" and a value of 39. There is no need to return any value. Thanks!

  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in...

    python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictionary (using inheritance), it also defines an auxiliary/attribute dictionary that uses the bidict’s values as keys, associated to a set of the bidict’s keys (the keys associated with that value). Remember that multiple keys can associate to the same value, which is why we use a set: since keys are hashable (hashable = immutable) we can store them in...

  • Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file...

    Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following: How to format each dictionary item as a text string in the input file. How to covert each input string into a dictionary item. How to format each item of your inverted dictionary as a text string in the output file. Create an input file with your original...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT