稍微整理一下,日常常摸的集合處理需要:
| 工具 | 運算子 | C++11(STL) | C#(.NET | 用途範例 | 分類 |
| 找集合內符合條件 | Predicate | find_if() | Find() | 在多個向量中找符合單位長度的向量(第一個) | Non-modifying sequence operations(不更動序列順序/內容) |
| 對每個元素執行操作 | Action | for_each() | ForEach() | 輸出向量內容 | Non-modifying sequence operations(不更動序列順序/內容 |
| 檢測集合內所有元素是否都符合條件 | Predicate | all_of() | All() | 是否每個向量皆為單位向量 | Non-modifying sequence operations(不更動序列順序/內容 |
| 檢測集合內是否至少有一元素符合條件 | Predicate | any_of() | Any() | 集合內至少有一向量與參考向量正交 | Non-modifying sequence operations(不更動序列順序/內容 |
| 計算集合內符合條件的元素數量 | Predicate | count() | Count() | 集合內符合單位向量定義的向量數量 | Non-modifying sequence operations(不更動序列順序/內容 |
| 集合型態轉換 | UnaryOperator | transform() | Select() | 轉換向量長 |
Modifying sequence operations(原序列內容更動
|
| 集合順序累加成單一元素 | BinaryOperator | 無 | Aggrerate() | 多組向量拼成矩陣 |
對應的運算子列表:
| C++11(STL) | C#(.NET | ||||
| 運算子 | 名稱 | 原型 | 名稱 | 原型 | 備註 |
| Predicate | UnaryPredicate | bool foo(T element) | Predicate<T> | bool foo(T element) | |
| Action | Function | void foo(T element) | Action | void foo(T element) | |
| UnaryOperator | UnaryOperator | T2 foo(T1 element) | Func<TSource,TResult> | Func<TSource,TResult> | 回傳值型別TResult |
| BinaryOperator | N/A | N/A | Func<TAccumulate,TSource,TAccumulate> | Func<TAccumulate,TSource,TAccumulate> | 回傳值型別TAccumulate |
做了一點小小練習,操作STL容器-array,元素為自定義的結構MyVector,用來表達簡單的二維向量;並且用STL-algorithm操作匯總輸出/找單位向量/算向量長,熟用集合處理的話就都是一行斬喔
#include<algorithm>
#include<array>
#include<math.h>
#include<iostream>
using namespace std;
typedef struct myVector
{
float x;
float y;
} MYVECTOR;
bool thePredicate(MYVECTOR vector)
{
return sqrt(pow(vector.x,2)+pow(vector.y,2)) == 1;
}
void theAction(MYVECTOR vector)
{
printf("%f,%f\n",vector.x,vector.y);
}
float theUnaryOperator(MYVECTOR vector)
{
return sqrt(pow(vector.x,2)+pow(vector.y,2));
}
int main(int argc, char const *argv[])
{
std::array<MYVECTOR,5> v;
std::array<float,5> lengths;
v[0].x = 2; v[0].y = 3;
v[1].x = 4; v[1].y = 5;
v[2].x = 6; v[2].y = 7;
v[3].x = 0; v[3].y = 1;
std::array<MYVECTOR,5>::iterator it = std::find_if(v.begin(),v.end(),thePredicate);
theAction(*it);
std::for_each(v.begin(),v.end(),theAction);
std::transform(v.begin(),v.end(),lengths.begin(),theUnaryOperator);
return 0;
}
參考1:STL algorithms
參考2: MSDN - Collection.Generic / Linq
沒有留言:
張貼留言