简介
accumulate
fill
accumulate
对指定范围内的元素求和,然后结果再加上一个由val指定的初始值。
- 需要引入
include<numeric>
template<class _InIt,
class _Ty> inline
_Ty accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{ // return sum of _Val and all in [_First, _Last)
return (_STD accumulate(_First, _Last, _Val, plus<>()));
}
fill
将输入值赋给标志范围内的所有元素。
template<class _FwdIt,
class _Ty> inline
void fill(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)
{ // copy _Val through [_First, _Last)
_DEBUG_RANGE(_First, _Last);
_Fill_unchecked(_Unchecked(_First), _Unchecked(_Last), _Val);
}
示例
#include "stdafx.h"
#include "stdafx.h"
#include "iostream"
#include "string"
#include "algorithm"
#include "vector"
#include "list"
#include <functional>
#include<numeric>
using namespace std;
class Student {
private:
int number;
string name;
public:
Student() {
}
Student(int number, string name) {
cout << "构造 " << number << " " << name.c_str() << endl;
this->number = number;
this->name = name;
}
Student(const Student & stu) {
//cout << "copy构造" <<stu.getNumber()<<" "<<stu.getName().c_str()<< endl;
this->number = stu.getNumber();
this->name = stu.getName();
}
~Student() {
//cout<<"析构 " << this->number << " " << this->name.c_str() << endl;
}
Student& operator=(const Student& stu) {
this->number = stu.getNumber();
this->name = stu.getName();
return *this;
}
void print()const {
cout << "print 》》 " << this->number << " " << this->name.c_str() << endl;
}
int getNumber() const {
return this->number;
}
string getName()const {
return this->name;
}
};
void printStuV(vector<Student> v) {
cout << "开始遍历vector<Student>============" << endl;
for (vector<Student>::iterator it = v.begin(); it != v.end(); it++) {
it->print();
}
cout << "结束遍历vector<Student>============" << endl;
}
void printNum(vector<int>v) {
cout << "开始遍历vector<int>============" << endl;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
cout << "结束遍历vector<int>============" << endl;
}
struct ReplaceFunc
{
bool operator()(const Student & stu1) const {
cout << "ReplaceFunc》》" << endl;
return stu1.getNumber() >3;
}
};
int main()
{
//accumulate示例,需要include<numeric>
vector<int> vNum;
vNum.push_back(1);
vNum.push_back(3);
vNum.push_back(5);
int sum = accumulate(vNum.begin(), vNum.end(), 100);
cout << "accumulate sum " << sum << endl;
//将输入值赋给标志范围内的所有元素。
vector<Student> vStu;
vStu.push_back(Student(1, "one"));
vStu.push_back(Student(2, "two"));
vStu.push_back(Student(3, "three"));
fill(vStu.begin() + 1, vStu.end(), Student(10, "fill"));
printStuV(vStu);
}
结果:
fill.png
网友评论