C++ 純粋仮想関数

#include <iostream>
#include <vector>
using namespace std;

struct Character {
    virtual void action() = 0;
};

struct Warrior : public Character {
    void action() { cout << "Warrior attacks with a sword!" << endl; }
};

struct Mage : public Character {
    void action() { cout << "Mage casts a fireball!" << endl; }
};

int main() {
    Warrior w;
    w.action();
    Mage m;
    m.action();

    vector<Character*> characters = { &w, &m };
    for (auto c : characters) {
        c->action();
    }
}

C++ デストラクタ

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Person {
	string name;
	Person(const string& newName) : name(newName) {}
	~Person() {
		cout << name << "は解体された\n";
	}
};

int main() {
	Person a1("Taro");
	Person* pA2 = new Person("Jiro");
	Person* pA3 = new Person("Saburo");
	auto pA4 = make_shared<Person>("Shiro");
	cout << a1.name << endl;
	cout << pA2->name << endl;
	cout << pA3->name << endl;
	cout << pA4->name << endl;

	delete pA2;
}

C++ search

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v{ 2,3,5,1,4 };
    auto begin = v.cbegin();
    auto end = v.cend();

    int target = 3;
    auto pos = find(begin, end, target);
    if (pos == end)
        cout << "見つからない\n";
    else
        cout << "見つかった: " << *pos << endl; // 出力値: 見つかった: 3

    target = 6; // Correcting typo from 'traget' to 'target'
    pos = find(begin, end, target);
    if (pos == end)
        cout << "見つからない\n"; // 出力値: 見つからない
    else
        cout << "見つかった: " << *pos << endl;

    return 0;
}

C++ 反復子

#include <iostream>
#include <vector>
#include <list>
#include <numeric>

template <typename T>
int total(T first, T last) {
    int sum = 0;
    for (T p = first; p != last; ++p) sum += *p;
    return sum;
}

int main() {
    std::vector<int> v{ 1, 2, 3, 4, 5 };
    std::cout << total(v.begin(), v.end()) << std::endl;
    std::cout << std::accumulate(v.begin(), v.end(), 0) << std::endl;

    int a[] = { 1, 2, 3, 4, 5 };
    std::cout << total(std::begin(a), std::end(a)) << std::endl;
    std::cout << std::accumulate(std::begin(a), std::end(a), 0) << std::endl;

    std::list<int> li{ 1, 2, 3, 4, 5 };
    std::cout << total(li.begin(), li.end()) << std::endl;
    std::cout << std::accumulate(li.begin(), li.end(), 0) << std::endl;

    return 0;
}