search
HomeBackend DevelopmentC++C++ program to update dictionary value by key

C++ program to update dictionary value by key

Aug 28, 2023 pm 10:37 PM
c programkey updateDictionary 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>

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>

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 );
}

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

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 );
}

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

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C   XML Libraries: Comparing and Contrasting OptionsC XML Libraries: Comparing and Contrasting OptionsApr 22, 2025 am 12:05 AM

There are four commonly used XML libraries in C: TinyXML-2, PugiXML, Xerces-C, and RapidXML. 1.TinyXML-2 is suitable for environments with limited resources, lightweight but limited functions. 2. PugiXML is fast and supports XPath query, suitable for complex XML structures. 3.Xerces-C is powerful, supports DOM and SAX resolution, and is suitable for complex processing. 4. RapidXML focuses on performance and parses extremely fast, but does not support XPath queries.

C   and XML: Exploring the Relationship and SupportC and XML: Exploring the Relationship and SupportApr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

C# vs. C  : Understanding the Key Differences and SimilaritiesC# vs. C : Understanding the Key Differences and SimilaritiesApr 20, 2025 am 12:03 AM

The main differences between C# and C are syntax, performance and application scenarios. 1) The C# syntax is more concise, supports garbage collection, and is suitable for .NET framework development. 2) C has higher performance and requires manual memory management, which is often used in system programming and game development.

C# vs. C  : History, Evolution, and Future ProspectsC# vs. C : History, Evolution, and Future ProspectsApr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

C# vs. C  : Learning Curves and Developer ExperienceC# vs. C : Learning Curves and Developer ExperienceApr 18, 2025 am 12:13 AM

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

C# vs. C  : Object-Oriented Programming and FeaturesC# vs. C : Object-Oriented Programming and FeaturesApr 17, 2025 am 12:02 AM

There are significant differences in how C# and C implement and features in object-oriented programming (OOP). 1) The class definition and syntax of C# are more concise and support advanced features such as LINQ. 2) C provides finer granular control, suitable for system programming and high performance needs. Both have their own advantages, and the choice should be based on the specific application scenario.

From XML to C  : Data Transformation and ManipulationFrom XML to C : Data Transformation and ManipulationApr 16, 2025 am 12:08 AM

Converting from XML to C and performing data operations can be achieved through the following steps: 1) parsing XML files using tinyxml2 library, 2) mapping data into C's data structure, 3) using C standard library such as std::vector for data operations. Through these steps, data converted from XML can be processed and manipulated efficiently.

C# vs. C  : Memory Management and Garbage CollectionC# vs. C : Memory Management and Garbage CollectionApr 15, 2025 am 12:16 AM

C# uses automatic garbage collection mechanism, while C uses manual memory management. 1. C#'s garbage collector automatically manages memory to reduce the risk of memory leakage, but may lead to performance degradation. 2.C provides flexible memory control, suitable for applications that require fine management, but should be handled with caution to avoid memory leakage.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools