I very often encounter the problem that I want to implement a data structure, and would like to allow users to expand its functionality; this is to add functionality, but not bytes to the data structure. An example would be the extension std :: vector with the sum method:
#include <iostream>
#include <vector>
template<>
int std::vector<int>::sum();
template<>
int std::vector<int>::sum() {
int s=0;
for(auto v = this->begin(); v!=this->end(); ++v) s+=*v;
return s;
}
int main() {
std::vector<int> numbers;
numbers.push_back(5);
numbers.push_back(2);
numbers.push_back(6);
numbers.push_back(9);
std::cout << numbers.sum() << std::endl;
return 0;
}
See: http://ideone.com/YyWs5r
So this is illegal, since you cannot add functions to a class like this. Obviously, this is some kind of design decision C ++ (11). It can be circumvented in two ways: definition
int sum(std::vector<int> &v) { ... }
std:: sort, , ++ (11). , , , ++. std::vector. , , , () . , , , , . , , std:: sort w.r.t. .
std::vector, , :
- , , . , , () . , - , .
- , , sum_vector mean_vector .
" ++", , ( ++ ). , , . ? , ; ?
: , , , , , , .