शुरुआती C/C++ अभ्यास

Remove Duplicate Values

यह शुरुआती exercise Remove Duplicate Values के जरिए core syntax और problem solving का अभ्यास कराती है।

Remove Duplicate Values क्या है?

यह शुरुआती exercise Remove Duplicate Values के जरिए core syntax और problem solving का अभ्यास कराती है।

Remove Duplicate Values को C और C++ दोनों में runnable code से हल करें।

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

  • Compiler warnings चालू करके सभी ठीक करें।
  • हर value का type और lifetime समझें।
  • Input और array bounds validate करें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>
int main(void) {
    int input[] = {1, 2, 1, 3, 2, 4}, output[6], size = 0;
    // Keep the first occurrence of every value.
    for (int i = 0; i < 6; ++i) { int seen = 0; for (int j = 0; j < size; ++j) if (output[j] == input[i]) seen = 1; if (!seen) output[size++] = input[i]; }
    for (int i = 0; i < size; ++i) printf("%s%d", i ? " " : "", output[i]); puts("");
}
अपेक्षित output
1 2 3 4
C++
कोड चलाएँ →
main.cpp
#include <iostream>
#include <unordered_set>
#include <vector>
int main() {
    std::vector input{1, 2, 1, 3, 2, 4}; std::vector<int> output; std::unordered_set<int> seen;
    // Insert returns true only for the first occurrence.
    for (int value : input) if (seen.insert(value).second) output.push_back(value);
    for (size_t i = 0; i < output.size(); ++i) std::cout << (i ? " " : "") << output[i]; std::cout << '\n';
}
अपेक्षित output
1 2 3 4

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

C और C++ implementations की तुलना करें, input बदलें और अतिरिक्त edge cases test करें।

C

C छोटे procedural APIs और representation details स्पष्ट करता है।

C++

C++ low-level model रखकर safer library types जोड़ता है।

अभ्यास

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

  • Invalid और boundary inputs जोड़ें।
  • -Wall -Wextra -Wpedantic से compile करें।
  • Declarations और implementation अलग करें।