C/C++ Data Structures

C में struct और C++ में class

C struct data group करता है; C++ class private state और methods से invariants बचाता है।

C में struct और C++ में class क्या है?

C struct data group करता है; C++ class private state और methods से invariants बचाता है।

संबंधित state और behavior model करें।

महत्वपूर्ण बातें

  • Operations से पहले invariants तय करें।
  • Empty, full और allocation-failure cases संभालें।
  • Complexity और ownership साथ मापें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

typedef struct {
    const char *owner;
    double balance;
} Account;

void deposit(Account *account, double amount) {
    if (amount > 0) {
        account->balance += amount;
    }
}

int main(void) {
    Account account = {"Ada", 100.0};
    deposit(&account, 25.0);
    printf("%s: %.2f\n", account.owner, account.balance);
    return 0;
}
अपेक्षित output
Ada: 125.00
C++
कोड चलाएँ →
main.cpp
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>

class Account {
    std::string owner_;
    double balance_;

public:
    Account(std::string owner, double balance)
        : owner_(std::move(owner)), balance_(balance) {}

    void deposit(double amount) {
        if (amount > 0) {
            balance_ += amount;
        }
    }

    void print() const {
        std::cout << owner_ << ": " << std::fixed
                  << std::setprecision(2) << balance_ << '\n';
    }
};

int main() {
    Account account("Ada", 100.0);
    account.deposit(25.0);
    account.print();
}
अपेक्षित output
Ada: 125.00

C और C++ की तुलना

C functions को struct pointer देता है। C++ class balance private रखकर valid methods से बदलता है।

C

Structures और operations अलग, allocation स्पष्ट होता है।

C++

Classes और containers invariants और resources manage करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Empty और capacity boundary tests जोड़ें।
  • Cleanup लागू कर leaks जाँचें।
  • Standard container से तुलना करें।