Table of Contents
Syntax for defining map data structure
Update the syntax of elements within the map
algorithm
Example
Output
Update after search
in conclusion
Home Backend Development C++ C++ program to update dictionary value by key

C++ program to update dictionary value by key

Aug 28, 2023 pm 10:37 PM
c program key update Dictionary value update

C++ program to update dictionary value by key

Many computer languages ​​provide a dictionary, which is a data structure. Dictionary is a faster data structure that stores data based on keys and values. It preserves key-value combinations so that keys can be easily searched for certain components in near real-time. The C STL language standard includes dictionary-like data structures. The term "map" is used to describe this data structure. This map creates a pair of keys and values ​​of any type (since we are using C, the types must be defined before compilation). This section demonstrates how to update values ​​in an existing map or dictionary in C.

Let’s first look at the definition of map data structure. These internal templates require two different types. The syntax and necessary libraries are shown below -

Syntax for defining map data structure

#include <map>
map<type1, type2=""> mapVariable;
</type1,></map>
Copy after login

In this case, we must import the "map" library to use the map data structure. Data types 1 and 2 are required for this. The data type of the key parameter is type1, and the data type of the value parameter is type2. Here the object derived from the map type class is mapVariable. Now let's see how to get it using a C map.

In a map data structure, we can put values ​​into the map by accessing existing keys or new keys. Since we are talking about updating values ​​here, we have to update the existing key. Keys will be used within square brackets like array index notation. Let's look at the syntax of this -

Update the syntax of elements within the map

mapVariable [<the key="" value="">] = <the new="" value="">;
</the></the>
Copy after login

algorithm

  • Created dictionary or map D

  • Existing key value k

  • The value of new key k v

  • Update like D[ k ] = v

  • Return D

Example

#include <iostream> 
#include <map> 
using namespace std;

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "ABCD", 25 },
        { "EFGH", 50 },
        { "IJKL", 75 },
        { "MNOP", 100 },
        { "QRST", 125 }
   };
   
   cout << "Before updation: " << endl;
   display( givenMap );
  
   cout << "After Updation: " << endl;
   
   //update the value of MNOP to 500
   givenMap[ "MNOP" ] = 500; 
   display( givenMap );
}
Copy after login

Output

Before updation: 
Key: ABCD, value: 25
Key: EFGH, value: 50
Key: IJKL, value: 75
Key: MNOP, value: 100
Key: QRST, value: 125
After Updation: 
Key: ABCD, value: 25
Key: EFGH, value: 50
Key: IJKL, value: 75
Key: MNOP, value: 500
Key: QRST, value: 125
Copy after login

In this method, we successfully updated the value by accessing the key parameter. However, this process may not always be accurate. This procedure has a serious drawback, which is that the given key may not exist in the map. But by using this process it will insert new key with given value. So in the next method we will see how to search and update an element after a successful search.

You can use the find() function in the map object to check whether a key exists in the map. It will return a pointer reference to the key, otherwise it will return the "end()" pointer to the map, which indicates that the map does not contain an element within it. Let us see the algorithm and implementation for better understanding.

algorithm

  • Created dictionary or map D

  • Existing key value k

  • The value of new key k v

  • Create an iterator object itr to obtain the pointer of the key-value pair

  • Call the find() method to put the dictionary D into itr

  • If itr is not the end of D, it means the key exists, then

    • Put v into itr

  • End if

Example

#include <iostream> 
#include <map> 
using namespace std;

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}

void updateElement( map <string, int>& givenMap, string givenKey, int newValue ){
   map <string, int>::iterator itr;
   itr = givenMap.find( givenKey );
   if( itr != givenMap.end() ){   // when item has found
      itr->second = newValue;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "ABCD", 25 },
        { "EFGH", 50 },
        { "IJKL", 75 },
        { "MNOP", 100 },
        { "QRST", 125 }
   };
   
   cout << "Before updation: " << endl;
   display( givenMap );
  
   cout << "After Updation: " << endl;
   
   //update the value of MNOP to 500
   updateElement( givenMap, "MNOP", 1580 );
   display( givenMap );
}
Copy after login

Output

Before updation: 
Key: ABCD, value: 25
Key: EFGH, value: 50
Key: IJKL, value: 75
Key: MNOP, value: 100
Key: QRST, value: 125
After Updation: 
Key: ABCD, value: 25
Key: EFGH, value: 50
Key: IJKL, value: 75
Key: MNOP, value: 1580
Key: QRST, value: 125
Copy after login

In this method, the updateElement function takes as input the map, the existing key, and newValue. Then search for that key. Just update the value if it exists, otherwise just derive it from the function. So by using this method we cannot create new entries in the map but can only update existing entries.

in conclusion

In this article, we learned how to update elements in a map using keys. In the first method, we use the direct assignment method, which successfully updates the element, but it can also add new elements when the key does not exist yet. The second method eliminates this problem by starting with a simple search. Sometimes we may notice that the second method takes extra time to search for the key and then update it. Therefore, it requires more search time than the first method. But if we think carefully, in the first method, this discovery is also essentially realized. Since the data structure uses hash-based techniques, it will run in constant time (in most cases).

The above is the detailed content of C++ program to update dictionary value by key. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Translate the following into Chinese: C program to convert Roman numerals to decimal numbers Translate the following into Chinese: C program to convert Roman numerals to decimal numbers Sep 05, 2023 pm 09:53 PM

Given below is a C language algorithm to convert Roman numerals to decimal numbers: Algorithm Step 1 - Start Step 2 - Read Roman numerals at runtime Step 3 - Length: = strlen(roman) Step 4 - For i=0 to Length-1 Step 4.1-switch(roman[i]) Step 4.1.1-case'm': &nbs

C++ program to compare the lexicographic order of two strings C++ program to compare the lexicographic order of two strings Sep 04, 2023 pm 05:13 PM

Lexicographic string comparison means that strings are compared in dictionary order. For example, if there are two strings 'apple' and 'appeal', the first string will come last because the first three characters of 'app' are the same. Then for the first string the character is 'l' and in the second string the fourth character is 'e'. Since 'e' is shorter than 'l', it will come first if we sort lexicographically. Strings are compared lexicographically before being arranged. In this article, we will see different techniques for lexicographically comparing two strings using C++. Using the compare() function in C++ strings The C++string object has a compare()

C program to find length of linked list C program to find length of linked list Sep 07, 2023 pm 07:33 PM

Linked lists use dynamic memory allocation, i.e. they grow and shrink accordingly. They are defined as collections of nodes. Here, a node has two parts, data and links. The representation of data, links and linked lists is as follows - Types of linked lists There are four types of linked lists, as follows: - Single linked list/Singly linked list Double/Doubly linked list Circular single linked list Circular double linked list We use the recursive method to find the length of the linked list The logic is -intlength(node *temp){ if(temp==NULL) returnl; else{&n

C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument Sep 17, 2023 am 10:49 AM

Hyperbolic functions are defined using hyperbolas instead of circles and are equivalent to ordinary trigonometric functions. It returns the ratio parameter in the hyperbolic sine function from the supplied angle in radians. But do the opposite, or in other words. If we want to calculate an angle from a hyperbolic sine, we need an inverse hyperbolic trigonometric operation like the hyperbolic inverse sine operation. This course will demonstrate how to use the hyperbolic inverse sine (asinh) function in C++ to calculate angles using the hyperbolic sine value in radians. The hyperbolic arcsine operation follows the following formula -$$\mathrm{sinh^{-1}x\:=\:In(x\:+\:\sqrt{x^2\:+\:1})}, Where\:In\:is\:natural logarithm\:(log_e\:k)

C program uses rename() function to change file name C program uses rename() function to change file name Sep 21, 2023 pm 10:01 PM

The rename function changes a file or directory from its old name to its new name. This operation is similar to the move operation. So we can also use this rename function to move files. This function exists in the stdio.h library header file. The syntax of the rename function is as follows: intrename(constchar*oldname,constchar*newname); The function of the rename() function accepts two parameters. One is oldname and the other is newname. Both parameters are pointers to constant characters that define the old and new names of the file. Returns zero if the file was renamed successfully; otherwise, returns a nonzero integer. During a rename operation

C++ program to print dictionary C++ program to print dictionary Sep 11, 2023 am 10:33 AM

A map is a special type of container in C++ in which each element is a pair of two values, namely a key value and a map value. The key value is used to index each item, and the mapped value is the value associated with the key. Regardless of whether the mapped value is unique, the key is always unique. To print map elements in C++ we have to use iterator. An element in a set of items is indicated by an iterator object. Iterators are primarily used with arrays and other types of containers (such as vectors), and they have a specific set of operations that can be used to identify specific elements within a specific range. Iterators can be incremented or decremented to reference different elements present in a range or container. The iterator points to the memory location of a specific element in the range. Printing a map in C++ using iterators First, let's look at how to define

C++ program to check if a character is alphabetic or non-alphabetic C++ program to check if a character is alphabetic or non-alphabetic Sep 14, 2023 pm 03:37 PM

Using strings or characters is sometimes very useful when solving some logic programming problems. A string is a collection of characters, which is a 1-byte data type used to hold symbols in ASCII values. Symbols can be English letters, numbers, or special characters. In this article, we will learn how to check if a character is an English letter or a letter of the alphabet using C++. Checking the isalpha() function To check if a number is a letter, we can use the isalpha() function in the ctype.h header file. This takes a character as input and returns true if it is an alphabet, false otherwise. Let us look at the following C++ implementation to understand the usage of this function. The Chinese translation of Example is: show

C++ program to get the imaginary part of a given complex number C++ program to get the imaginary part of a given complex number Sep 06, 2023 pm 06:05 PM

Modern science relies heavily on the concept of plural numbers, which was first established in the early 17th century by Girolamo Cardano, who introduced it in the 16th century. The formula for complex numbers is a+ib, where a holds the html code and b is a real number. A complex number is said to have two parts: the real part <a> and the imaginary part (<ib>). The value of i or iota is √-1. The plural class in C++ is a class used to represent complex numbers. The complex class in C++ can represent and control several complex number operations. Let's take a look at how to represent and control the display of plural numbers. imag() member function As mentioned above, complex numbers are composed of real part and imaginary part. To display the real part we use real()

See all articles