std::vector<double> temperatures {65, 75, 56, 48, 31, 28, 32, 29, 40, 41, 44, 50}; std::copy(std::begin(temperatures), std::end(temperatures), //List the values std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; auto average = std::accumulate(std::begin(temperatures),std::end(temperatures), 0.0)/temperatures.size(); std::cout << "Average temperature: "<< average << std::endl; std::partition(std::begin(temperatures), std::end(temperatures),[average](double t) { return t < average; }); std::copy(std::begin(temperatures), std::end(temperatures),std::ostream_iterator<doiible>{std::cout, " "}); std::cout << std::endl;這段程式碼會輸出下面這些內容:
65 75 56 48 31 28 32 29 40 41 44 50
Average temperature: 44.9167
44 41 40 29 31 28 32 48 56 75 65 50
using gender = char; using first = string; using second= string; using Name = std::tuple<first, second, gender>; std:: vector<Name> names {std::make_tuple ("Dan", "old", 'm'),std::make_tuple("Ann", "old", 'f'),std::make_tuple ("Ed", "old",'m'),std::make_tuple ("Jan", "old", 'f'), std::make_tuple ("Edna", "old", 'f')}; std::partition(std::begin(names), std::end(names),[](const Names name) { return std::get<2>(name) == 'f'; }); for(const auto& name : names) std:: cout << std::get<0> (name) << " "<< std::get<1> (name) << std::endl;這裡使用 using 宣告來解釋 tuple 物件成員變數的意義。當 tuple 物件的最後一個成員變數是“f”時,這個謂詞會返回 true,所以輸出中會出現 Edna、Ann 以及處在 Ed 和 Dan 之前的 Jan。在這個謂詞中,可以用表示式 std::get<gender>(name) 來參照 tuple 的第三個成員變數。這樣做是可行的,因為第三個成員是唯一的,這就允許用它的型別來識別這個成員。
std::stable_partition(std::begin(temperatures), std::end(temperatures),[average](double t) { return t < average; });做出這些修改後,對應的輸出如下:
65 75 56 48 31 28 32 29 40 41 44 50
Average temperature: 44.9167
31 28 32 29 40 41 44 65 75 56 48 50