accumulate, copy, 및 vector::push_back
사용 하는 방법을 보여 줍니다 있는 축적, 복사, 및 vector::push_back Visual C++에서 표준 템플릿 라이브러리 (STL) 함수.
template<class InputIterator, class _TYPE> inline
_TYPE accumulate(
InputIterator First,
InputIterator Last,
_TYPE Init
)
template<class InputIterator, class _TYPE, class BinaryOperator> inline
_TYPE accumulate(
InputIterator First,
InputIterator Last,
_TYPE Init,
BinaryOperator Binary_Op
)
설명
[!참고]
프로토타입에 클래스/매개 변수 이름은 헤더 파일에서 버전이 일치 하지 않습니다.일부 가독성을 높이기 위해 수정 되었습니다.
축적 STL 함수 초기화 축 열기 acc 초기 값 초기화를 하며 수정 된 acc = acc + *i 또는 acc = Binary_Op(acc, *i) 모든 반복기에 대 한 i 범위에서 [First, Last) 순서 대로.일반적으로 accumulate STL 함수 숫자 요소 벡터의 합계를 계산 하는 데 사용 됩니다.그러나이 또한 문자열 벡터를 연결 하는 등 다른 작업을 사용할 수 있습니다.
예제
// accumulate.cpp
// compile with: /EHsc
//
// Description of accumulate(first,last,init)
// accumulate(first,last,init,binary_op):
//
// Initializes the accumulator acc with the initial value init
// acc = init
// and then modifies it with
// acc = acc + *i
// or
// acc = binary_op(acc, *i)
// for every iterator i in the range [first, last) in order.
// turn off warning about symbols too long for debugger
#pragma warning (disable : 4786)
#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
typedef vector < float > FloatArray;
typedef vector < string > StringArray;
typedef ostream_iterator <float, char, char_traits <char> > FloatOstreamIt;
int main ()
{
// a vector of floats
FloatArray rgFA;
// an ostream iterator that outputs a float to cout terminated
// by a space
FloatOstreamIt OstreamIt(cout," ");
// Initialize the array to 1,1/2,1/3,...
for (int i=0; i<10; i++) rgFA.push_back(1.0f/(i+1));
// Print the array
copy(rgFA.begin(),rgFA.end(),OstreamIt);
cout << endl;
// Sum the array
cout << "The sum of 1 + 1/2 + 1/3 + ... + 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),0.0f)
<< endl;
// Compute the product of the array
cout << "The product of 1 * 1/2 * 1/3 * ... * 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),1.0f,multiplies<float>())
<< endl;
// Initialize array of strings
StringArray rgs;
rgs.push_back("This ");
rgs.push_back("is ");
rgs.push_back("one ");
rgs.push_back("sentence. ");
// Concatenate the strings in the array and print the sentence
cout << "The concatenated vector of strings: "
<< accumulate(rgs.begin(),rgs.end(),string(""))
<< endl;
}
Output
1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 0.111111 0.1
The sum of 1 + 1/2 + 1/3 + ... + 1/10 is 2.92897
The product of 1 * 1/2 * 1/3 * ... * 1/10 is 2.75573e-007
The concatenated vector of strings: This is one sentence.
요구 사항
헤더: <numeric>