Stary zapis:
bool success = init(x);
if (success) {
    cout << "x new value: " << x << endl;
}
Nowy zapis ze średnikiem (od C++17):if (bool success = init(x); success) {
    cout << "x new value: " << x << endl;
}
Nie widziałem niczego podobnego w innych językach, ale wydaje się całkiem eleganckie. Poniżej przykład z std::map::insert, który zwraca dwie wartości:  iterator na element (świeżo wstawiony lub stary o tym samym kluczu) oraz flagę informującą czy wstawienia się powiodło.#include <iostream>
#include <string>
#include <map>
using namespace std;
void insert_to_map(std::map<int, string>& m, std::pair<int, string> p) {
    if (auto [it, success] = m.insert(p); success) {
        cout << "success, new elem: " << it->first << " -> " << it->second << endl;
    } else {
        cout << "fail, old elem:    " << it->first << " -> " << it->second << endl;
    }
}
int main() {
    std::map<int, string> m = { {1, "aaa"} } ;
    auto b = std::make_pair(2, "bbb");
    insert_to_map(m, std::move(b));
    auto c = std::make_pair(1, "ccc");
    insert_to_map(m, std::move(c));
    for (const auto& v : m) {
        cout << v.first << " " << v.second << endl;
    }
}
Wynik:success, new elem: 2 -> bbb fail, old elem: 1 -> aaa 1 aaa 2 bbb
 
Brak komentarzy:
Prześlij komentarz