#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++
C++ sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v{ 2 ,3 , 5, 1, 4 };
sort(v.begin(), v.end());
for (auto i : v) cout << i << ", ";
cout << endl;
int a[] = { 2,3,5,1,4 };
sort(begin(a), end(a));
for (auto i : a) cout << i << ",";
cout << endl;
}
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;
}
C++ 再帰
include<iostream>
using namespace std;
int fibonacci(int n) {
if (n < 3) return 1;
return fibonacci(n – 1) + fibonacci(n – 2);
}
int main() {
for (int n = 1; n <= 10; ++n) {
cout << “f(” << n << “) = ” << fibonacci(n) << endl;
}
}
C++ 静的変数
include<iostream>
using namespace std;
int f() {
static int x = 0;
++x;
return x;
}
int main()
{
cout << f() << endl;
cout << f() << endl;
cout << f() << endl;
}
C++ ローカル変数
include<iostream>
using namespace std;
int f() {
int x = 0;
++x;
return x;
}
int main()
{
cout << f() << endl;
cout << f() << endl;
cout << f() << endl;
}
C++ 約数を数える関数
include<iostream>
using namespace std;
int main()
{
int n, divisors;
n = 10;
divisors = 0;
for (int i = 1; i <= n; ++i) {
if (n % i == 0) ++divisors;
}
cout << n << "の約数の数:" << divisors << endl;
}
C++ return
include<iostream>
using namespace std;
int add1(int x) {
return x + 1;
}
int main()
{
int result = add1(1);
cout << result << endl;
}
C++ Hello
include<iostream>
using namespace std;
void sayHello(int times) {
for (int i = 0; i < times; ++i) {
cout << “Hello, World\n”;
}
}
int main()
{
sayHello(5);
}
C++ dowhile
include<iostream>
using namespace std;
int main()
{
int i = 0;
do {
cout << “Hello, World\n”;
++i;
} while (i < 5);
}