Skip to content

Instantly share code, notes, and snippets.

@hiramekun
Last active August 26, 2018 08:03
Show Gist options
  • Save hiramekun/32233f1b60c4dcfcef7779e43ae8ac9d to your computer and use it in GitHub Desktop.
Save hiramekun/32233f1b60c4dcfcef7779e43ae8ac9d to your computer and use it in GitHub Desktop.
c++のvectorの操作
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <cmath>
#include <numeric>
using namespace std;
int main() {
vector<int> v = { 3, 5, 2, 4, 1 };
printf("begin address: %d\n", v.begin());
printf("max element address: %d\n", max_element(v.begin(), v.end()));
printf("max element: %d\n", *max_element(v.begin(), v.end()));
printf("max element idx: %d\n", max_element(v.begin(), v.end()) - v.begin());
// 配列の和を計算.
printf("sum all: %d\n", accumulate(v.begin(), v.end(), 0));
// 配列の掛け算をしたものを計算.
printf("multiple all: %d\n", accumulate(v.begin(), v.end(), 1, multiplies<int>()));
// 部分和を求める.
vector<int> w(5); // 先に要素数分のメモリを確保.
partial_sum(v.begin(), v.end(), w.begin());
for (int i = 0; i < w.size(); i++) {
printf("to index %d: %d\n", i, w[i]);
}
return 0;
}
@hiramekun
Copy link
Author

実行結果

begin address: 21163040
max element address: 21163044
max element: 5
max element idx: 1
sum all: 15
multiple all: 120
to index 0: 3
to index 1: 8
to index 2: 10
to index 3: 14
to index 4: 15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment