[:tr]Herkese merhabalar arkadaşlar,
Bu yazım ile birlikte “Kod Parçası” serimize bir başlangıç yapıyoruz. Bundan sonra, bu tarz çok daha kısa, öz ve daha kolay sindirilebilecek 🙂 kod parçalarını, Haftalık C++ yazıları altında sizler ile paylaşıyor olacağım. Daha önce yazdığım değerlendirme yazımda da bahsettiğim gibi bu tarz kısa kod paylaşımlarını aslında uzun süredir yapmayı planlıyordum (ve düzenli hale getirme). Bu kod parçaları:
- ya çok bilinen bir problemi çözüyor olacak,
- ya yaygın olarak gerçekleştirilen bir kullanıma yönelik olacak,
- ya da C++ ile gelen yeni kabiliyetleri göstermeye yönelik olacak.
Bu yazıları “Snippet/Kod Parçası” olarak etiketleyeceğim ama halen Haftalık C++ serisi altında olacak.
İlk kod parçamız if-init, yapısal bağlama, ilklendirme listeleri ve auto kullanıma yönelik kombo bir kod parçası olacak 🙂
Bu arada bu konulara ilişkin daha detaylı bilgi almak için aşağıdaki yazılarıma muhakkak göz atınız lütfen 😉
Haftalık C++ 3 – if/switch init-statements
Haftalık C++ 4 – Yapısal Bağlama
Modern C++ (1): nullptr, enum sınıfları, range-based döngüler, auto
Modern C++ (3): Uniform Initialization, override/final, default/delete, constexpr, etc.
Yukarıdaki yazılarımı okuduysanız, bu kabiliyetlerin konteynerler ile kullanıma ilişkin örnekler de verdiğimi görürsünüz. Fakat aşağıdaki vereceğim kod parçası, özellikle std::map konteynerine veri ekleme de kullanabileceğiniz oldukça kullanışlı bir kod parçası. Bu konteynere veri eklemek için std::map::insert() API’sini kullanabilirsiniz, bu durumda ilgili API size bir std::pair döner. Bunun ilk elemanı ya yeni eklenen elemana (eğer daha önce konteynerde yok ise) ya da mevcut elemanı işaret eden bir iterator’dür. İkincisi ise ekleme işleminin başarılı bir şekilde olup/olmadığını ifade eden bir boolean değerdir. Bu API’nin detaylarına sayfasından‘ dan ulaşabilirsiniz. Şimdi, bu işin daha önce (modern C++’tan önce) ve şu an nasıl yapıldığına bakalım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> #include <map> #include <string> using namespace std; // Modern C++ öncesi int main() { map<string, int> mapInstance; mapInstance["hello"] = 1; mapInstance["world"] = 2; pair<map<string, int>::iterator, bool> ret; // Zaten var olan ve yeni bir eleman ekleyelim ret = mapInstance.insert ( pair<string, int>("hello", 500) ); if (ret.second == false) cout << "Element 'hello' already exists with value: " << ret.first->second << '\n'; ret = mapInstance.insert ( pair<string, int>("there", 500) ); if (ret.second == false) cout << "Element 'there' already exists with value: " << ret.first->second << '\n'; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <map> #include <string> using namespace std; // Modern C++ hali int main() { map<string, int> mapInstance = { {"hello", 1}, {"world", 2}}; // Zaten var olan ve yeni bir eleman ekleyelim if (auto [it, inserted] = mapInstance.insert({ "hello", 3 }); !inserted) cout << "Element 'hello' already exists with value: " << it->second << "\n"; if (auto [it, inserted] = mapInstance.insert({ "there", 4 }); !inserted) cout << "Element 'there' already exists with value: " << it->second << "\n"; return 0; } |
Benim şahsi kanaatim, ikinci, yani modern C++ kod parçası çok daha açık ve şık, bu sebeple size de bunu kullanmanızı önereceğim. Evet, hepsi bu kadar. Size kısa sürecek demiştim 🙂
Bu arada sırada son std::thread yazımın çevirisi var, sonrasında son bir std::thread yazımız ile o diziyi de bitirmeyi planlıyorum. Şu an ayrıca, Python kodu ile C++ uyumlu bir kod parçasının birlikte kullanılmasına yönelik bir proje üzerinde de çalışıyorum. Bu eminim bir çoğunuzun ilginizi çekecek, en kısa sürede bu konu ile ilgili de sizler ile yazılar paylaşacağım.
O zamana kadar, kendinize iyi bakın. Mutlu kodlamalar :)[:en]Hello everybody,
This is the first post of my snippets series that I am initiating. These posts will still be under weekly C++, but much shorter and can be swallowed very quicly 🙂
As I mentioned in my assessment post, one thing that I would like to do share is relatively short code snippets. These code snippets will either solve a well known problem or more commonly shows the new feature/ability of programming language which will be C++ mostly.
I will tags these posts as “Snippet” but under “Weekly C++” series so that you can filter them out easily.
The first snippet will be about the usage of if-initializer, structured binding, initializer-list and auto (all three together 🙂 for a well-known usage.
By the way, to get more information about these topics, you can check out my posts about these topics:
Weekly C++ 3 – if/switch init-statements
Weekly C++ 4 – Structured Binding
Modern C++ (1): nullptr, enum sınıfları, range-based döngüler, auto
Modern C++ (3): Uniform Initialization, override/final, default/delete, constexpr, etc.
Well, if you read the above posts, you probably seen the possible usage of these features with containers. Following snippet is also very useful for std::map container which shows the usage for std::map insert() API. When you use insert() API of map, it returns a pair where the first element points to either the newly added element (if it is not already added) or the element that has same key value (previously added element). The second one is a boolean variable that indicates whether the insert operation succeeded or not. The details of API can be found here. Now let us, look at two code snippets that perform same task in both pre-modern C++ and modern C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> #include <map> #include <string> using namespace std; // Pre Modern C++ version int main() { map<string, int> mapInstance; mapInstance["hello"] = 1; mapInstance["world"] = 2; pair<map<string, int>::iterator, bool> ret; // add already existing and new element ret = mapInstance.insert ( pair<string, int>("hello", 500) ); if (ret.second == false) cout << "Element 'hello' already exists with value: " << ret.first->second << '\n'; ret = mapInstance.insert ( pair<string, int>("there", 500) ); if (ret.second == false) cout << "Element 'there' already exists with value: " << ret.first->second << '\n'; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <map> #include <string> using namespace std; // Modern C++ version int main() { map<string, int> mapInstance = { {"hello", 1}, {"world", 2}}; // add already existing and new element if (auto [it, inserted] = mapInstance.insert({ "hello", 3 }); !inserted) cout << "Element 'hello' already exists with value: " << it->second << "\n"; if (auto [it, inserted] = mapInstance.insert({ "there", 4 }); !inserted) cout << "Element 'there' already exists with value: " << it->second << "\n"; return 0; } |
The second one (modern way) seems to be more clearer and elegant than the first one, in my humble opinion, of course 🙂
By the way, I have a tranlation post for our last thread post, then I am planning to complete our thread series with one last post. Currently, I am also working on a project about using Modern C++ from Pyhton which may attract some of you, so I will also share the details as soon as possbile.
Till then, take care of yourselves and happy coding :)[:]
