返回第一个为true的元素。
找不到则返回最后一个元素。
#include <iostream>
#include <algorithm>
#include <vector>
bool IsOdd(int i)
{
return ((i % 2) == 1);
}
int main()
{
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if(myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n'; //25
return 0;
}
#include <iostream>
#include <functional>
double my_divide(double x, double y)
{
return x / y;
}
struct MyPair
{
double a;
double b;
double multiply()
{
return a * b;
}
};
int main()
{
using namespace std::placeholders;
auto fn_five = std::bind(my_divide, 10, 2); //return 10/2
std::cout << fn_five() << "\n";
auto fn_half = std::bind(my_divide, _1, 2); //return x/2
std::cout << fn_half(10) << "\n";
auto fn_invert = std::bind(my_divide, _2, _1); //return y/x
std::cout << fn_invert(10, 2) << '\n';
auto fn_rounding = std::bind<int>(my_divide, _1, _2); //return int(10/3)
std::cout << fn_rounding(10, 3) << "\n";
MyPair ten_two{ 10, 2 };
auto bound_member_fn = std::bind(&MyPair::multiply, _1); //return x.multiply()
std::cout << bound_member_fn(ten_two) << '\n';
auto bound_member_data = std::bind(&MyPair::a, ten_two); //return ten_two.a
std::cout << bound_member_data() << '\n';
auto bound_member_data_2 = std::bind(&MyPair::a, _1); //return x.a
std::cout << bound_member_data(ten_two) << '\n';
return 0;
}
#include <iostream>
#include <functional>
std::function<size_t(const char*)> print_func;
size_t CPrint(const char * pcStr)
{
std::cout << pcStr << '\n';
return 0;
}
class CxxPrint
{
public:
size_t operator()(const char * pcStr)
{
std::cout << pcStr << '\n';
return 0;
}
};
int main()
{
print_func = CPrint;
print_func("Hello World");
CxxPrint p;
print_func = p;
print_func("Hello CxxPrint");
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
// 4. capture of class member
class A
{
public:
//capture member by this
void DoSomethins1()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [this](int i) {
return i > m_min_val && i < m_max_val;
});
}
//capture member by default pass-by-value
void DoSomethins2()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [=](int i) {
return i > m_min_val && i < m_max_val;
});
}
//capture member by default pass-by-reference
void DoSomethins3()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [&](int i) {
return i > m_min_val && i < m_max_val;
});
}
private:
std::vector<int> m_vec;
int m_min_val;
int m_max_val;
};
int main()
{
//1. simple lambda
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if(myvector.begin(), myvector.end(), [](int i) {
return ((i % 2) == 1);
});
std::cout << "The first odd value is " << *it << '\n'; //25
//2. lambda return syntax
std::function<int(int)> square = [](int i) -> int { return i * i; };
std::cout << square(10) << "\n";
//3. capture of local variable
/*
[a,&b] 其中 a 以复制捕获而 b 以引用捕获。
[this] 以引用捕获当前对象( *this )
[&] 以引用捕获所有用于 lambda 体内的自动变量,并以引用捕获当前对象,若存在
[=] 以复制捕获所有用于 lambda 体内的自动变量,并以引用捕获当前对象,若存在
[] 不捕获
*/
{
int min_val = 10;
int max_val = 100;
auto it = std::find_if(myvector.begin(), myvector.end(), [=](int i) {
return i > min_val && i < max_val;
});
auto it1 = std::find_if(myvector.begin(), myvector.end(), [&](int i) {
return i > min_val && i < max_val;
});
auto it2 = std::find_if(myvector.begin(), myvector.end(), [=, &max_val](int i) {
return i > min_val && i < max_val;
});
}
return 0;
}
vector 可以动态的变大。
array 是固定大小的,就是一个普通的数组,可以使用迭代器。
#include <iostream>
#include <array>
std::array<int, 3> global; //initialized as: {0,0,0}
int main()
{
std::array<int, 3> first; //uninitialized
std::array<int, 3> second = { 10, 20 }; //initialized as: {10,20,0}
std::array<int, 3> third = { 1, 2, 3 }; //initialized as: {1,2,3}
std::array<int, 3> fourth = third;
for (auto x : fourth)
std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
返回一个引用。
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myarray;
for (int i = 0; i < 10; i++)
myarray.at(i) = i + 1;
std::cout << "myarray contains:";
for (int i = 0; i < 10; i++)
std::cout << ' ' << myarray.at(i);
std::cout << '\n';
return 0;
}
front() 返回第一个元素的引用。
back() 返回最后一个元素的引用。
#include <iostream>
#include <array>
int main()
{
std::array<int, 3> myarray = { 2, 16, 77 };
std::cout << "front is: " << myarray.front() << std::endl;
std::cout << "back is: " << myarray.back() << std::endl;
myarray.front() = 100;
myarray.back() = 99;
for (int & x : myarray)
std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
#include <iostream>
#include <array>
int main()
{
std::array<int, 5> myarray = { 2, 16, 77, 34, 50 };
for (auto it = myarray.begin(); it != myarray.end(); ++it)
{
std::cout << ' ' << *it;
}
std::cout << '\n';
return 0;
}
size() 和 max_size() 好像是一样的。
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myints;
std::cout << "size of myints: " << myints.size() << std::endl; //10
std::cout << "max_size of myints: " << myints.max_size() << std::endl; //10
std::cout << "sizeof(myints): " << sizeof(myints) << std::endl; //40
return 0;
}
返回指向第一个元素的指针。
#include <iostream>
#include <cstring>
#include <array>
int main()
{
const char * cstr = "Test string";
std::array<char, 12> charray;
std::memcpy(charray.data(), cstr, 12);
std::cout << charray.data() << '\n';
return 0;
}
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myarray;
unsigned int i;
for (i = 0; i < 10; i++)
myarray[i] = i;
for (i = 0; i < 10; i++)
std::cout << ' ' << myarray[i];
std::cout << '\n';
return 0;
}
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
int main(int argc, char * argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
udp::resolver resolver(io_service);
udp::resolver::query query(udp::v4(), argv[1], "daytime");
udp::endpoint receiver_endpoint = *resolver.resolve(query);
udp::socket socket(io_service);
socket.open(udp::v4());
boost::array<char, 1> send_buf = { {0} };
socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);
boost::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
std::cout.write(recv_buf.data(), len);
}
catch (std::exception & e)
{
std::cerr << "catch error: " << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std;
time_t now = time(0);
return ctime(&now);
}
int main(int argc, char * argv[])
{
try
{
boost::asio::io_service io_service;
udp::socket socket(io_service, udp::endpoint(udp::v4(), 13));
for (;;)
{
boost::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
boost::system::error_code error;
socket.receive_from(boost::asio::buffer(recv_buf),
remote_endpoint, 0, error);
if (error && error != boost::asio::error::message_size)
throw boost::system::system_error(error);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
socket.send_to(boost::asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception & e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std;
time_t now = time(0);
return ctime(&now);
}
class udp_server
{
public:
udp_server(boost::asio::io_service & io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_),
remote_endpoint,
boost::bind(&udp_server::handle_receive,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
void handle_receive(const boost::system::error_code & error, std::size_t)
{
if (!error || error == boost::asio::error::message_size)
{
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string())
);
socket_.async_send_to(
boost::asio::buffer(*message),
remote_endpoint,
boost::bind(&udp_server::handle_send,
this,
message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string>,
const boost::system::error_code &,
std::size_t)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
udp_server server(io_service);
io_service.run();
}
catch (std::exception & e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = make_daytime_string();
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this()));
}
private:
tcp_connection(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
void handle_write()
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
tcp::acceptor acceptor_;
};
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error));
}
void handle_receive(const boost::system::error_code& error)
{
if (!error || error == boost::asio::error::message_size)
{
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message));
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string> /*message*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <iostream>
#include <memory>
struct C { int * data; };
int main()
{
std::shared_ptr<int> p1;
std::shared_ptr<int> p2(nullptr);
std::shared_ptr<int> p3(new int);
std::cout << "p1: " << p1.use_count() << "\n"; // 0
std::cout << "p2: " << p2.use_count() << "\n"; // 0
std::cout << "p3: " << p3.use_count() << "\n"; // 1
std::shared_ptr<int> p4(new int, std::default_delete<int>());
std::shared_ptr<int> p5(new int, [](int*p) {delete p; }, std::allocator<int>());
std::shared_ptr<int> p6(p5);
std::cout << "p4: " << p4.use_count() << "\n"; // 1
std::cout << "p5: " << p5.use_count() << "\n"; // 2
std::cout << "p6: " << p6.use_count() << "\n"; // 2
std::shared_ptr<int> p7(std::move(p6));
std::cout << "p7: " << p7.use_count() << "\n"; // 2
std::cout << "p6: " << p6.use_count() << "\n"; // 0
std::shared_ptr<int> p8(std::unique_ptr<int>(new int));
std::shared_ptr<C> obj(new C);
std::shared_ptr<int> p9(obj, obj->data);
std::cout << "p8: " << p8.use_count() << "\n"; // 1
std::cout << "p9: " << p9.use_count() << "\n"; // 2
return 0;
}
use_count() 应该就是返回指向该内存的指针的数量。
获取指针的值
#include <iostream>
#include <memory>
int main()
{
int * p = new int(10);
std::shared_ptr<int> a(p);
if (a.get() == p)
{
std::cout << "a and p point to the same location\n";
}
std::cout << *a.get() << "\n";
std::cout << *a << "\n";
std::cout << *p << "\n";
return 0;
}
/*
output:
a and p point to the same location
10
10
10
*/
如果 use_count() == 1 返回true。否则返回false。
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> foo;
std::shared_ptr<int> bar(new int);
std::cout << "1 foo: " << foo.unique() << "\n"; // 0
std::cout << "1 bar: " << bar.unique() << "\n"; // 1
foo = bar;
std::cout << "2 foo: " << foo.unique() << "\n"; // 0
std::cout << "2 bar: " << bar.unique() << "\n"; // 0
bar = nullptr;
std::cout << "2 foo: " << foo.unique() << "\n"; // 1
std::cout << "2 bar: " << bar.unique() << "\n"; // 0
return 0;
}
重载bool运算符
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> foo;
std::shared_ptr<int> bar(new int(34));
if (foo) std::cout << "foo points to " << *foo << "\n";
else std::cout << "foo is null\n";
if (bar) std::cout << "bar points to " << *bar << '\n';
else std::cout << "bar is null\n";
return 0;
}
重载取值运算符
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> foo(new int);
std::shared_ptr<int> bar(new int(100));
*foo = *bar * 2;
std::cout << "foo: " << *foo << "\n"; //200
std::cout << "bar: " << *bar << "\n"; //100
return 0;
}
It returns the same value as get().
#include <iostream>
#include <memory>
struct C { int a; int b; };
int main()
{
std::shared_ptr<C> foo;
std::shared_ptr<C> bar(new C);
foo = bar;
foo->a = 10;
foo->b = 20;
std::cout << "foo: " << foo->a << " " << foo->b << "\n";
std::cout << "bar: " << bar->a << " " << bar->b << "\n";
return 0;
}
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> foo;
std::shared_ptr<int> bar(new int(10));
foo = bar; //copy
bar = std::make_shared<int>(20); //move
std::unique_ptr<int> unique(new int(30));
foo = std::move(unique); //move from unique_ptr
std::cout << "*foo: " << *foo << '\n'; //30
std::cout << "*bar: " << *bar << '\n'; //20
return 0;
}
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> sp;
sp.reset(new int);
*sp = 10;
std::cout << *sp << '\n'; //10
sp.reset(new int);
*sp = 20;
std::cout << *sp << '\n'; //20
sp.reset();
return 0;
}
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> foo(new int(10));
std::shared_ptr<int> bar(new int(20));
foo.swap(bar);
std::cout << "*foo: " << *foo << '\n'; //20
std::cout << "*bar: " << *bar << '\n'; //10
return 0;
}
#include <iostream>
#include <memory>
int main()
{
int * pInt = new int[100];
std::shared_ptr<int> sp1(pInt);
std::shared_ptr<int> sp2(pInt); //会Crash,因为内存被释放了两次。
return 0;
}
#include <iostream>
#include <memory>
class tester
{
public:
tester(){}
~tester() {}
std::shared_ptr<tester> getTester()
{
return std::shared_ptr<tester>(this);
}
};
int main()
{
tester t;
std::shared_ptr<tester> sp = t.getTester(); //会crash,析构函数释放了一次,shared_ptr释放了一次。
return 0;
}
要用enable_shared_from_this