std::vector<int> s = {1, 2, 3, 4}; for(auto& i : s){ std::cout << i << std::endl; }
functor
A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator().
// C++ program to demonstrate working of // functors.
usingnamespacestd; // A Functor class { private: int num; public: increment(int n) : num(n) { } // This operator overloading enables calling // operator function () on objects of increment intoperator()(int arr_num)const{ return num + arr_num; } };
intmain() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); int to_add = 5; transform(arr, arr+n, arr, increment(to_add)); for (int i=0; i<n; i++) cout << arr[i] << " "; }
structTask { int mId; Task(int id ) :mId(id) { std::cout<<"Task::Constructor"<<std::endl; } ~Task() { std::cout<<"Task::Destructor"<<std::endl; } };
intmain() { // Create a unique_ptr object through raw pointer std::unique_ptr<Task> taskPtr(new Task(23)); // auto taskPtr = new Task(23); //leak //Access the element through unique_ptr int id = taskPtr->mId;
近期评论