[問題] 請問 copy+back_inserter 還有哪些用法?
最近突發奇想,想把clase當成Container來用,以下是一個範例:
http://src.wtgstudio.com/?dVl32d
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
template <typename T>
class MyStatistics {
private:
T m_Amount, m_Summation, m_Summation4Square;
public:
typedef MyStatistics<T> this_type;
explicit inline MyStatistics(void): m_Amount(T()), m_Summation(T()),
m_Summation4Square(T()) {}
virtual inline ~MyStatistics(void) {}
public: /*
copy & back_inserter Requirement
*/
typedef T& reference;
typedef const T& const_reference;
inline this_type& push_back(const_reference e) {
return AddElement(e);
}
public: /*
for_each Requirement
*/
inline MyStatistics(const this_type& d): m_Amount(d.m_Amount),
m_Summation(d.m_Summation), m_Summation4Square(d.m_Summation4Square) {}
inline this_type& operator=(const this_type& d) {
if (this != &d) {
m_Amount = d.m_Amount;
m_Summation = d.m_Summation;
m_Summation4Square = d.m_Summation4Square;
}
return *this;
}
inline this_type& operator()(const T& e) {
return AddElement(e);
}
public:
inline this_type& AddElement(const T& e = T()) {
m_Amount += 1;
m_Summation += e;
m_Summation4Square += e * e;
return *this;
}
inline this_type& Clear(void) {
m_Amount = T();
m_Summation = T();
m_Summation4Square = T();
return *this;
}
inline const T& GetNum(void) const {
return m_Amount;
}
inline const T& GetSum(void) const {
return m_Summation;
}
inline const double CalAverage(void) const {
return m_Summation / double(m_Amount);
}
inline const double CalStandardDeviation(void) const {
return sqrt(m_Summation4Square / double(m_Amount) -
CalAverage()*CalAverage());
}
};
template <typename T>
inline ostream& operator <<(ostream& os, const MyStatistics<T>& d) {
return os << "Summation/Amount: " << d.GetSum() << "/ " << d.GetNum() <<
"\n"
<< "Average,Standard Deviation: " << d.CalAverage() << ", "
<< d.CalStandardDeviation() << "\n" ;
}
int main(int argc, char* argv[]) {
int ia[] = {4, 5, 5, 6, 3, 3, 4, 5, 3, 4, 2, 3, 6, 4, 5, 5, 23, 5, 5, 3, 6,
7, 3, 7};
typedef vector<int> myIntArray_type;
myIntArray_type myInstWidth_c(ia, ia + sizeof(ia) / sizeof(ia[0]));
MyStatistics<int> a;
copy(myInstWidth_c.begin(), myInstWidth_c.end(), back_inserter(a));
cout << a << endl;
a = for_each(myInstWidth_c.begin(), myInstWidth_c.end(),
MyStatistics<int>());
cout << a << endl;
system("PAUSE");
return 0;
}
不知道這樣使用back_inserter是不是太邪魔歪道 >_<
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.195.88.23
※ 編輯: chrisdar 來自: 123.195.88.23 (05/10 00:03)
→
05/10 01:57, , 1F
05/10 01:57, 1F
→
05/10 03:03, , 2F
05/10 03:03, 2F
推
05/10 07:23, , 3F
05/10 07:23, 3F
→
05/10 07:23, , 4F
05/10 07:23, 4F
※ 編輯: chrisdar 來自: 123.195.88.23 (05/10 07:59)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章