如何完成如下要求???只需要点思路~~~~
编写模板函数,为std::vector重载 << 运算符,从而可以让vector通过标准流输出。以确保如下代码可以正常编译运行。
int main( int argc, char** argv )
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
std::vector<int> v( array, array + sizeof(array) / sizeof(int) );
std::cout << v << std::endl;
return 0;
}
在控制台中输出:1 2 3 4 5 6 7 8
(2) 进阶要求:把该函数改为用<algorithm>头文件中的for_each算法实现。为此,需要编写一个函数对象,作为for_each的第三个参数。
我想问如何去重载vector中的运算符,它不已经标准化了吗??
还有函数对象是一个类吗???具体包括哪些东西??
[解决办法]
1 我猜。
template <class T>friend ostream& operator << <T> (ostream& , Vector<T>);
[解决办法]
建议还是自己定义类模板继承与vector吧。然后重载<<
[解决办法]
#inlcude <ioforward>
然后重载<<操作符
[解决办法]
#include <iostream>using namespace std;template <typename T>class vector{private: T *arr; //定义的数据存储方式 int size;//元素个数public : vector(T *array, T *size);//构造函数 ~vector(); friend ostream &operator<< (ostream &os,const vector&v) { for(int i=0; i < v.size; ++i) os<<" "<<v.arr[i]; return os; }};template <typename T>vector<T>::vector(T *array, T *Length){ int i=0; size=(Length-array); arr=new T[(Length-array)*sizeof(T)]; while(array != Length) { arr[i]=*array++; i++; }}template <typename T>vector<T>::~vector(){ delete []arr;}int _tmain(int argc, _TCHAR* argv[]){ int array[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; vector<int> v( array, array + sizeof(array) / sizeof(int) ); cout << v << endl; return 0;}第二题: for_each(...,...,function f),你写个函数就行了,把函数的名称代替f就成了。其它的应该没啥问题了
[解决办法]
#include <iostream>#include <vector>#include <algorithm>template <class T>struct printer{ void operator()(T obj) { std::cout << obj << " "; }};template <class T>std::ostream& operator <<(std::ostream &os, std::vector<T> &obj){ //for (typename std::vector<int>::iterator it = obj.begin(); it != obj.end(); ++it) // std::cout << *it << " "; std::for_each(obj.begin(), obj.end(), printer<T>()); return os;}int main(void){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; std::vector<int> v(arr, arr + sizeof(arr) / sizeof(int)); std::cout << v << std::endl; return 0;}