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...

  • 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...

  • 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...

  • I need some help i need to do this in C# Objectives: • Create an application...

    I need some help i need to do this in C# Objectives: • Create an application that uses a dictionary collection to store information about an object. • Understanding of abstract classes and how to use them • Utilize override with an abstract class • Understanding of Interfaces and how to use them • Implement an Interface to create a “contract” between classes. • Compare and contrast inheritance and interfaces. Instructions: Interface: Create an interface called ITrainable which contains the...

  • We will build one Python application via which users can perform various analytics tasks on data...

    We will build one Python application via which users can perform various analytics tasks on data in 2-D table (similar to Spreadsheet) format which looks like: Column Name 1 Column Name 2 Column Name 3 Column Name N … … … … … In this table, each row represents the data of one object that we are interested in. Columns, on the other hand, represent the attributes of these objects. For example, this table could represent students’ academic records. Each...

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
ADVERTISEMENT