c_cpp 一个方便的东西,只是常见结构的一些空类型和检查它们的方法。 <br/>来自此SO的想法:http://stackoverflow.com/questi

一个方便的东西,只是常见结构的一些空类型和检查它们的方法。 <br/>来自此SO的想法:http://stackoverflow.com/questions/11987142/sending-nil-to-cgpoint-type-parameter

ABNullStructs.h
const CGPoint ABCGPointNull  =  {(CGFloat)NAN, (CGFloat)NAN};
const UIOffset ABUIOffsetNull =  {(CGFloat)NAN, (CGFloat)NAN};
const CGSize ABCGSizeNull   =  {(CGFloat)NAN, (CGFloat)NAN};

BOOL ABCGPointIsNull( CGPoint point ){
    return isnan(point.x) && isnan(point.y);
}
BOOL ABUIOffsetIsNull( UIOffset offset ){
    return isnan(offset.horizontal) && isnan(offset.vertical);
}
BOOL ABCGSizeIsNull( CGSize size ){
    return isnan(size.width) && isnan(size.height);
}

c_cpp Macros.h

Macros.h
#define ApplicationDelegate                 ((AppDelegate *)[[UIApplication sharedApplication] delegate])
#define UserDefaults                        [NSUserDefaults standardUserDefaults]
#define NotificationCenter                  [NSNotificationCenter defaultCenter]
#define SharedApplication                   [UIApplication sharedApplication]
#define Bundle                              [NSBundle mainBundle]
#define MainScreen                          [UIScreen mainScreen]
#define ShowNetworkActivityIndicator()      [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
#define HideNetworkActivityIndicator()      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
#define NetworkActivityIndicatorVisible(x)  [UIApplication sharedApplication].networkActivityIndicatorVisible = x
#define NavBar                              self.navigationController.navigationBar
#define TabBar                              self.tabBarController.tabBar
#define NavBarHeight                        self.navigationController.navigationBar.bounds.size.height
#define TabBarHeight                        self.tabBarController.tabBar.bounds.size.height
#define ScreenWidth                         [[UIScreen mainScreen] bounds].size.width
#define ScreenHeight                        [[UIScreen mainScreen] bounds].size.height
#define TouchHeightDefault                  44
#define TouchHeightSmall                    32
#define ViewWidth(v)                        v.frame.size.width
#define ViewHeight(v)                       v.frame.size.height
#define ViewX(v)                            v.frame.origin.x
#define ViewY(v)                            v.frame.origin.y
#define SelfViewWidth                       self.view.bounds.size.width
#define SelfViewHeight                      self.view.bounds.size.height
#define RectX(f)                            f.origin.x
#define RectY(f)                            f.origin.y
#define RectWidth(f)                        f.size.width
#define RectHeight(f)                       f.size.height
#define RectSetWidth(f, w)                  CGRectMake(RectX(f), RectY(f), w, RectHeight(f))
#define RectSetHeight(f, h)                 CGRectMake(RectX(f), RectY(f), RectWidth(f), h)
#define RectSetX(f, x)                      CGRectMake(x, RectY(f), RectWidth(f), RectHeight(f))
#define RectSetY(f, y)                      CGRectMake(RectX(f), y, RectWidth(f), RectHeight(f))
#define RectSetSize(f, w, h)                CGRectMake(RectX(f), RectY(f), w, h)
#define RectSetOrigin(f, x, y)              CGRectMake(x, y, RectWidth(f), RectHeight(f))
#define DATE_COMPONENTS                     NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
#define TIME_COMPONENTS                     NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
#define FlushPool(p)                        [p drain]; p = [[NSAutoreleasePool alloc] init]
#define RGB(r, g, b)                        [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA(r, g, b, a)                    [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define HEXCOLOR(c)                         [UIColor colorWithRed:((c>>16)&0xFF)/255.0 green:((c>>8)&0xFF)/255.0 blue:(c&0xFF)/255.0 alpha:1.0];

#define IBOutletProperty @property (strong, nonatomic) IBOutlet
#define StrongProperty @property (strong, nonatomic)
#define AssignProperty @property (assign, nonatomic)
#define WeakProperty @property (nonatomic, weak)
#define DelegateProperty @property (nonatomic, weak) id delegate

//
//  Macros.h
//
//  Created by John Iacoviello on 11/26/11.
//

// Constants
#define APP_VERSION                             [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]
#define APP_NAME                                [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]
#define APP_DELEGATE                            [[UIApplication sharedApplication] delegate]
#define USER_DEFAULTS                           [NSUserDefaults standardUserDefaults]
#define APPLICATION                             [UIApplication sharedApplication]
#define BUNDLE                                  [NSBundle mainBundle]
#define MAIN_SCREEN                             [UIScreen mainScreen]
#define FILE_MANAGER                            [NSFileManager defaultManager]
#define DOCUMENTS_DIR                           [[FILE_MANAGER URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]
#define NAV_BAR                                 self.navigationController.navigationBar
#define TAB_BAR                                 self.tabBarController.tabBar
#define DATE_COMPONENTS                         NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
#define IS_PAD                                  ([[UIDevice currentDevice] interfaceIdiom] == UIUserInterfaceIdiomPad)

// Props
#define ScreenWidth                             [MAIN_SCREEN bounds].size.width
#define ScreenHeight                            [MAIN_SCREEN bounds].size.height
#define NavBarHeight                            self.navigationController.navigationBar.bounds.size.height
#define TabBarHeight                            self.tabBarController.tabBar.bounds.size.height
#define SelfBoundsWidth                         self.bounds.size.width
#define SelfBoundsHeight                        self.bounds.size.height
#define SelfFrameWidth                          self.frame.size.width
#define SelfFrameHeight                         self.frame.size.height
#define SelfViewBoundsWidth                     self.view.bounds.size.width
#define SelfViewBoundsHeight                    self.view.bounds.size.height
#define SelfViewFrameWidth                      self.view.frame.size.width
#define SelfViewFrameHeight                     self.view.frame.size.height
#define SelfX                                   self.frame.origin.x
#define SelfY                                   self.frame.origin.y
#define SelfViewX                               self.view.frame.origin.x
#define SelfViewY                               self.view.frame.origin.y

// Utils
#define clamp(n,min,max)                        ((n < min) ? min : (n > max) ? max : n)
#define distance(a,b)                           sqrtf((a-b) * (a-b))
#define point(x,y)                              CGPointMake(x, y)
#define append(a,b)                             [a stringByAppendingString:b];
#define fileExistsAtPath(path)                  [FILE_MANAGER fileExistsAtPath: path]

// Colors
#define hex_rgba(c)                             [UIColor colorWithRed:((c>>24)&0xFF)/255.0 green:((c>>16)&0xFF)/255.0 blue:((c>>8)&0xFF)/255.0 alpha:((c)&0xFF)/255.0]
#define hex_rgb(c)                              [UIColor colorWithRed:((c>>16)&0xFF)/255.0 green:((c>>8)&0xFF)/255.0 blue:((c)&0xFF)/255.0 alpha:1.0]

// Views Getters
#define frameWidth(v)                           v.frame.size.width
#define frameHeight(v)                          v.frame.size.height
#define boundsWidth(v)                          v.bounds.size.width
#define boundsHeight(v)                         v.bounds.size.height
#define posX(v)                                 v.frame.origin.x
#define posY(v)                                 v.frame.origin.y

// View Setters
#define setPosX(v,x)                            v.frame = CGRectMake(x, posY(v), frameWidth(v), frameHeight(v))
#define setPosY(v,y)                            v.frame = CGRectMake(posX(v), y, frameWidth(v), frameHeight(v))
#define setFramePosition(v,x,y)                 v.frame = CGRectMake(x, y, frameWidth(v), frameHeight(v))
#define setFrameSize(v,w,h)                     v.frame = CGRectMake(posX(v), posY(v), w, h)
#define setBoundsPosition(v,x,y)                v.bounds = CGRectMake(x, y, boundsWidth(v), boundsHeight(v))
#define setBoundsSize(v,w,h)                    v.bounds = CGRectMake(posX(v), posY(v), w, h)

// View Transformations
#define rotate(v,r)                             v.transform = CGAffineTransformMakeRotation(r / 180.0 * M_PI)
#define scale(v,sx,sy)                          v.transform = CGAffineTransformMakeScale(sx, sy)
#define animate(dur,curve,anims)                [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:dur]; [UIView setAnimationCurve:curve]; anims; [UIView commitAnimations]

// Notifications
#define addEventListener(id,s,n,o)              [[NSNotificationCenter defaultCenter] addObserver:id selector:s name:n object:o]
#define removeEventListener(id,n,o)             [[NSNotificationCenter defaultCenter] removeObserver:id name:n object:o]
#define dispatchEvent(n,o)                      [[NSNotificationCenter defaultCenter] postNotificationName:n object:o]
#define dispatchEventWithData(n,o,d)            [[NSNotificationCenter defaultCenter] postNotificationName:n object:o userInfo:d]

// User Defaults
#define boolForKey(k)                           [USER_DEFAULTS boolForKey:k]
#define floatForKey(k)                          [USER_DEFAULTS floatForKey:k]
#define integerForKey(k)                        [USER_DEFAULTS integerForKey:k]
#define objectForKey(k)                         [USER_DEFAULTS objectForKey:k]
#define doubleForKey(k)                         [USER_DEFAULTS doubleForKey:k]
#define urlForKey(k)                            [USER_DEFAULTS urlForKey:k]
#define setBoolForKey(v, k)                     [USER_DEFAULTS setBool:v forKey:k]
#define setFloatForKey(v, k)                    [USER_DEFAULTS setFloat:v forKey:k]
#define setIntegerForKey(v, k)                  [USER_DEFAULTS setInteger:v forKey:k]
#define setObjectForKey(v, k)                   [USER_DEFAULTS setObject:v forKey:k]
#define setDoubleForKey(v, k)                   [USER_DEFAULTS setDouble:v forKey:k]
#define setURLForKey(v, k)                      [USER_DEFAULTS setURL:v forKey:k]
#define saveUserDefaults()                      [USER_DEFAULTS synchronize]

// NSLog only in debug mode
#if DEBUG == 1
    #define Log(...) NSLog(__VA_ARGS__)
#else
    #define Log(...) do {} while (0)
#endif

c_cpp a thiefhttp://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id = 0042サンプルは通るのですがWAになりますよかったら间违い箇所を教えてください

a thiefhttp://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id = 0042サンプルは通るのですがWAになりますよかったら间违い箇所を教えてください

gistfile1.cpp
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cctype>

#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <algorithm>

using namespace std;

//#define deb_table(arr, w, h) rep(w_n, w){  rep(h_n, h) {cout << arr[w][h] << " "  } cout << endl; }
#define rep(i, n) for(int i = 0; i < n; i++)

// P(価値, 重さ)
typedef pair<int ,int> P;

class data
{
    public:
        int v;
        int w;
    public:
        data(int a, int b){ v=a; w=b;}
};

int case_num=1;
/*
風呂敷の耐えられる重さW(1000 以下)
お宝の数 N
お宝 1 の価値(整数), お宝 1 の重さ( < W:整数)
お宝 2 の価値(整数), お宝 2 の重さ( < W:整数)
.
.
.
お宝 N の価値(整数), お宝 N の重さ( < W:整数)
*/

int max( int a, int b)
{
    if(a > b) { return a;}
    else { return b; }
}

//
int solve()
{
    int w,n;
    vector<data> v;
    cin >> w;
    //終わりのときは-1を返す
    if(w == 0) { return -1; }

    cin >> n;
    int value, weight;

    //int dp[n+1][w+1];
    //dp[考えたインデックス][重さ]
    //インデックスは0から数えてnまで => [n+1]
    //重さは0から数えてwまで         => [w+1]
    int dp[n+1][w+1];
    //dp init
    rep(i,n+1)rep(j,w+1) dp[i][j] = 0;  

    rep(i, n)
    {
        scanf("%d,%d" ,&value, &weight);
        v.push_back( data(value, weight) );
    }

    //dp[何番目まで考えたか][重さ] = 最大値

    rep(i,n+1)
    {
        rep(j,w+1)
        {
            //dp[i][j]から二つ分岐、分岐先ではmaxをとる
            if(0 <= i && i < n && 0 <= j && j  <= w )
            {
                dp[i+1][j] = max(dp[i+1][j] , dp[i][j]);
                if ( j+v[i+1].w <= w )
                {
                    dp[i+1][j + v[i+1].w] = max(dp[i+1][j + v[i+1].w] , dp[i][j] + v[i+1].v);
                }
            }
        }
    }
    /*
    rep(i,n+1){
        cout << "[";
        rep(j,w+1){
            cout << dp[i][j] << " ";
        }
        cout << "]" << endl;
    }
    */
    //maxを取る値の最小の重さを探す
    int least_weight;
    rep(j,w){
         if(dp[n][j] < dp[n][j+1])
         {
             least_weight= j+1;
         }
    }
   
    cout << "Case " << case_num << ":" << endl;
    cout << dp[n][w] << endl;
    cout << least_weight<< endl;
    return 0;
}

int main()
{
    while (1)
    {
        if(solve() == -1){ break;};
        case_num++;
    }
}


c_cpp ROOT TH1类的简化基本功能

ROOT TH1类的简化基本功能

TH1_Sumw2.cxx
void TH1::Sumw2(Bool_t flag) // default flag = KTRUE
{
  if (!flag) {
    if (fSumw2.fN > 0 ) fSumw2.Set(0);
    return;
  }
  if (fSumw2.fN == fNcells) return;

  fSumw2.Set(fNcells);
  if (fEntries > 0)
    for (Int_t bin = 0; bin < fNcells; bin++) {
      fSumw2.fArray[bin] = TMath::Abs(GetBinContent(bin));
    }
}
TH1_SetBinError.cxx
void TH1::SetBinError(Int_t bin, Double_t error)
{
  if (!fSumw2.fN) Sumw2();
  fSumw2.fArray[bin] = error*error;
}
TH1_SetBinContent.cxx
void TH1D::SetBinContent(Int_t bin, Double_t content)
{
  // AbstractMethod, overridden by TH1D
  fEntries++;
  fTsumw = 0;   // stats[0]
  fArray[bin] = content;
}
TH1_ResetStats.cxx
void TH1::ResetStats()
{
  Double_t stats[kNstat] = {0}; // kNstat = 13
  fTsumw = 0;
  fEntries = 1; // to force re-calculation of the statistics in GetStats
  GetStats(stats);
  PutStats(stats);
  fEntries = TMath::Abs(fTsumw);
  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 )
    fEntries = stats[0]*stats[0]/stats[1];
}
TH1_PutStats.cxx
void TH1::PutStats(Double_t *stats)
{
  fTsumw   = stats[0];
  fTsumw2  = stats[1];
  fTsumwx  = stats[2];
  fTsumwx2 = stats[3];
}
TH1_GetStats.cxx
void TH1::GetStats(Double_t *stats) const
{
  if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
    for (bin = 0; bin < 4; bin++) stats[bin] = 0;
    // in original code include underflow/overflow if fgStatOverflows
    for (binx = firstBinX; binx <= lastBinX; binx++) {
      x   = fXaxis.GetBinCenter(binx);
      w   = GetBinContent(binx);
      err = TMath::Abs(GetBinError(binx));
      stats[0] += w;
      stats[1] += err*err;
      stats[2] += w*x;
      stats[3] += w*x*x;
    }
    // if (stats[0] < 0) do something ?!
  } else {
    stats[0] = fTsumw;
    stats[1] = fTsumw2;
    stats[2] = fTsumwx;
    stats[3] = fTsumwx2;
  }
}
TH1_GetEffectiveEntries.cxx
Double_t TH1::GetEffectiveEntries() const
{
  Stat_t s[kNstat];
  this->GetStats(s); // s[0] sum of weights, s[1] sum of squares of weights
  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]));
}
TH1_GetBinError.cxx
Double_t TH1::GetBinError(Int_t bin) const
{
  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
  return TMath::Sqrt(TMath::Abs(GetBinContent(bin)));
}
TH1_GetBinContent.cxx
Double_t TH1D::GetBinContent(Int_t bin) const
{
  // AbstractMethod, overridden by TH1D
  return Double_t (fArray[bin]);
}
TH1_Fill_1.cxx
Int_t TH1::Fill(Double_t x, Double_t w)
{
  Int_t bin = fXaxis.FindBin(x);
  fEntries++;
  AddBinContent(bin, w);
  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
  fTsumw   += w;      // stats[0]
  fTsumw2  += w*w;    // stats[1]
  fTsumwx  += w*x;    // stats[2]
  fTsumwx2 += w*x*x;  // stats[3]
  return bin;
}
TH1_Fill.cxx
Int_t TH1::Fill(Double_t x)
{
  Int_t bin = fXaxis.FindBin(x);
  fEntries++;
  AddBinContent(bin);
  if (fSumw2.fN) ++fSumw2.fArray[bin];
  ++fTsumw;           // stats[0]
  ++fTsumw2;          // stats[1]
  fTsumwx  += x;      // stats[2]
  fTsumwx2 += x*x;    // stats[3]
  return bin;
}
TH1_AddBinContent_1.cxx
void TH1D::AddBinContent(Int_t bin, Double_t w) {
  // AbstractMethod, overridden by TH1D (TH1.h)
  fArray[bin] += Double_t (w);
}
TH1_AddBinContent.cxx
void TH1D::AddBinContent(Int_t bin) {
  // AbstractMethod, overridden by TH1D (TH1.h)
  ++fArray[bin];
}

c_cpp 适用于ROOT TH1类的PrintWiki功能

适用于ROOT TH1类的PrintWiki功能

TH1_PrintWiki.cxx
void TH1::PrintWiki(Option_t * /*option*/) const
{
  if (fDimension > 1) {
    Info("PrintWiki", "only for 1D histo");
    return;
  }

  Int_t binx;
  Int_t firstx = 0, lastx = fXaxis.GetNbins()+1;
  Double_t x, bc, be, bsw2;

  Printf("{| class=\"wikitable\" style=\"text-align:center; font-family:monospace;\"");
  Printf("! colspan=\"4\" | %s, %s", GetName(), GetTitle());
  Printf("|-");
  Printf("| x[bin] || BinContent || BinSumw2 || BinError");

  for (binx = firstx; binx <= lastx; binx++) {
    x  = fXaxis.GetBinCenter(binx);
    bc = GetBinContent(binx);
    be = GetBinError(binx);
    if(fSumw2.fN) bsw2 = fSumw2.fArray[binx];
    else          bsw2 = TMath::Abs(0.0/0.0); // force NaN
    Printf("|-");
    Printf("| [%02d]=%g || %g || %g || %g", binx, x, bc, bsw2, be);
  }
  Printf("|-\n|\n|-");
  Printf("| fTsumw || fTsumw2 || fTsumwx || fTsumwx2");
  Printf("|-");
  Printf("| %g || %g ||  %g || %g", fTsumw, fTsumw2, fTsumwx, fTsumwx2);
  Printf("|-");
  Printf("| fEntries || Effective || RMS || Mean");
  Printf("|-");
  Printf("| %g || %g ||  %g || %g", fEntries, GetEffectiveEntries(), GetRMS(), GetMean());
  Printf("|}");
}

c_cpp 3767-I_Wanna_Go_Home.cpp

3767-I_Wanna_Go_Home.cpp
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

#define MAXN 610

struct EDGE {
  int a, b, c;
};

EDGE edge[ 10010 ];
vector< int > vertex[ MAXN ];
int cost[ MAXN ][ MAXN ];
int camp[ MAXN ], dist[ MAXN ];
bool visit[ MAXN ];
int n, e;

int dijkstra( int st, int ed ) {
	typedef pair< int, int > NODE;
	priority_queue< NODE, vector< NODE >, greater< NODE > > PQ;
	memset( visit, 0, sizeof( visit ) );
	memset( dist, 63, sizeof( dist ) );
	dist[ st ] = 0;
	PQ.push( pair< int, int >( dist[ st ], st ) );

	while ( !PQ.empty() ) {
		int now = PQ.top().second;
		PQ.pop();
		visit[ now ] = 1;
		for ( int i = 0; i < vertex[ now ].size(); ++i ) {
			int next = vertex[ now ][ i ];
			if ( !visit[ next ] && dist[ now ] + cost[ now ][ next ] < dist[ next ] ) {
				dist[ next ] = dist[ now ] + cost[ now ][ next ];
				PQ.push( pair< int, int >( dist[ next ], next ) );
			}
		}
	}
	return dist[ ed ] == dist[ 0 ] ? -1 : dist[ ed ];
}

int main() {

	while ( ~scanf( "%d", &n ) && n ) {
		
		scanf( "%d", &e );
		for ( int i = 1; i <= n; ++i )
			vertex[ i ].clear();
		int a, b, c;
		for ( int i = 0; i < e; ++i )
			scanf( "%d %d %d", &edge[ i ].a, &edge[ i ].b, &edge[ i ].c );

		for ( int i = 1; i <= n; ++i ) {
			scanf( "%d", &c );
			camp[ i ] = c;
		}

		for ( int i = 0; i < e; ++i ) {
			if ( camp[ edge[ i ].a ] == camp[ edge[ i ].b ] ) {
				cost[ edge[ i ].a ][ edge[ i ].b ] = cost[ edge[ i ].b ][ edge[ i ].a ] = edge[ i ].c;
				vertex[ edge[ i ].a ].push_back( edge[ i ].b ), vertex[ edge[ i ].b ].push_back( edge[ i ].a );
			}
			else if ( camp[ edge[ i ].a ] == 1 )
				cost[ edge[ i ].a ][ edge[ i ].b ] = edge[ i ].c, vertex[ edge[ i ].a ].push_back( edge[ i ].b );
			else
				cost[ edge[ i ].b ][ edge[ i ].a ] = edge[ i ].c, vertex[ edge[ i ].b ].push_back( edge[ i ].a );
		}
		printf( "%d\n", dijkstra( 1, 2 ) );
	}

	return 0;
}

c_cpp NSArray中对象的通用UITableView / UICollectionView数据源

NSArray中对象的通用UITableView / UICollectionView数据源

ADVIndexedSubscripting.h
//
//  Copyright © 2013 Yuri Kotov
//

#import <Foundation/Foundation.h>

@protocol ADVIndexedSubscripting <NSObject>
- (id) objectAtIndexedSubscript:(NSUInteger)index;
@end
ADVArrayDataSource.m
//
//  Copyright © 2013 Yuri Kotov
//

#import "ADVArrayDataSource.h"

@interface ADVArrayDataSource ()
@property (readonly, nonatomic) NSString *cellIdentifier;
@property (readonly, nonatomic) ADVCellConfigurationBlock configurationBlock;
@end

@implementation ADVArrayDataSource
{
    NSMutableArray *_array;
}

#pragma mark - ADVArrayDataSource
- (instancetype) initWithArray:(NSArray *)array
        reusableCellIdentifier:(NSString *)identifier
        cellConfigurationBlock:(ADVCellConfigurationBlock)block
{
    if ((self = [super init]))
    {
        _configurationBlock = block;
        _cellIdentifier = identifier;
        _array = [array mutableCopy];
    }
    return self;
}

- (NSInteger) numberOfItemsInSection:(NSInteger)section
{
    return self.array.count;
}

- (void) deleteObjectAtIndexPath:(NSIndexPath *)indexPath
{
    [_array removeObjectAtIndex:indexPath.row];
}

#pragma mark - ADVIndexedSubscripting
- (id) objectAtIndexedSubscript:(NSUInteger)index
{
    return self.array[index];
}

#pragma mark - UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self numberOfItemsInSection:section];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    self.configurationBlock(cell, self[indexPath.row]);
    return cell;
}

- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
 forRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (editingStyle)
    {
        case UITableViewCellEditingStyleDelete:
            [self deleteObjectAtIndexPath:indexPath];
            break;
        default:
            break;
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self numberOfItemsInSection:section];
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView
                   cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifier
                                                                           forIndexPath:indexPath];
    self.configurationBlock(cell, self[indexPath.row]);
    return cell;
}

@end
ADVArrayDataSource.h
//
//  Copyright © 2013 Yuri Kotov
//

#import <Foundation/Foundation.h>
#import "ADVIndexedSubscripting.h"

typedef void(^ADVCellConfigurationBlock)(id cell, id object);

@interface ADVArrayDataSource : NSObject <ADVIndexedSubscripting, UITableViewDataSource, UICollectionViewDataSource>

@property (readonly, nonatomic) NSArray *array;

- (instancetype) initWithArray:(NSArray *)array
        reusableCellIdentifier:(NSString *)identifier
        cellConfigurationBlock:(ADVCellConfigurationBlock)block;

@end

c_cpp FMDB基本使用

FMDB基本使用

DYLogKeeper.h
#import <Foundation/Foundation.h>

@interface DYLogKeeper : NSObject

@property(strong, nonatomic) NSString *localId;

@property(strong, nonatomic) NSDate *addtime;

@property(strong, nonatomic) NSString *deviceId;

@property(strong, nonatomic) NSString *content;

@property(strong, nonatomic) NSString *logkeeperId;

@property(nonatomic) int deviceType;

@property(nonatomic) int channel;


@end
DYLogKeeper+DB.m
#import "DYLogKeeper+DB.h"

#import "DYDB.h"
#import <FMDB/FMDatabase.h>
#import "DYUUID.h"
#import "NSDate+NSDateFormaterCategory.h"

DYLogKeeper * rs2logkeeper(FMResultSet *rs) {
  DYLogKeeper *obj = [[DYLogKeeper alloc] init];
	
	obj.localId = [rs stringForColumn:@"local_id"];
	obj.logkeeperId = [rs stringForColumn:@"logkeeper_id"];
	obj.addtime = [rs dateForColumn:@"add_time"];
	obj.content = [rs stringForColumn:@"content"];

	obj.deviceId = [rs stringForColumn:@"device_id"];
	obj.deviceType = [rs intForColumn:@"device_type"];
	obj.channel = [rs intForColumn:@"channel"];
	
	return obj;
}

@implementation DYLogKeeper (DB)

+ (void) createSqliteTable {
	
	DLog(@"check table is exists?");
	FMDatabase *db = [[DYDB sharedDB] connect];
	NSString *existsSql = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"log_keepers" ];
	DLog(@"%@", existsSql);
	
	FMResultSet *rs = [db executeQuery:existsSql];
	
	if ([rs next]) {
		NSInteger count = [rs intForColumn:@"countNum"];
		DLog(@"The table count: %d", count);
		if (count == 1) {
			DLog(@"log_keepers table is existed.");
			return;
		}
		
		DLog(@"log_keepers is not existed.");
	}
	[rs close];
	
	
	DLog(@"create table ....");
	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"log_keepers_table" ofType:@"sql"];
	DLog(@"logkeeper sql file: %@", filePath);
		
	NSError *error;
	NSString *sql = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
	
	if (error != nil) {
		DLog(@"fail to read sql file: %@", [error description]);
		return;
	}
	DLog(@"--sql: \n %@", sql);
	DLog(@"execute sql ....");
	if([db executeUpdate:sql]) {
		DLog(@"create table succes....");
	} else {
		DLog(@"fail to execute update sql..");
	}
	
	
	[db close];
}


+ (BOOL) insert: (DYLogKeeper *) logkeeper {
	DLog(@"insert logkeeper");
	DLog(@"convert int value to NSNumber ...");
	logkeeper.localId = [DYUUID uuidString];
	
	NSNumber *channelNum = [NSNumber numberWithInt:logkeeper.channel];
	DLog(@"-- channelNum: %@", channelNum);
	NSNumber *typeNumber = [NSNumber numberWithInt:logkeeper.deviceType];
	DLog(@"-- deviceType: %@", typeNumber);
	
	NSString *sql = @"insert into log_keepers(local_id, logkeeper_id, add_time, content, device_id, device_type, channel) values(?, ?, ?, ?, ?, ?, ?)";
	
	FMDatabase *db = [[DYDB sharedDB] connect];
	if (db == nil) {
		DLog(@"fail to create db..");
	}
	BOOL ret = [db executeUpdate:sql, logkeeper.localId, logkeeper.logkeeperId,
				logkeeper.addtime, logkeeper.content,
				logkeeper.deviceId, typeNumber, channelNum];
	
	[db close];

	return ret;
}

+ (BOOL) updateContent:(NSString *)content
			   localId: (NSString *)localId {
	
	DLog(@"update logkeeper content");
	NSString *sql = @"update log_keepers set content = ? where local_id = ?";
	
	FMDatabase *db = [[DYDB sharedDB] connect];
	BOOL ret = [db executeUpdate:sql, content, localId];
	
	[db close];
	return ret;
}

- (BOOL) remove: (DYLogKeeper *) logkeeper {
	DLog(@"remove logkeeper: %@", logkeeper.localId);
	NSString *sql = @"delete from log_keepers where local_id = ?";
		
	FMDatabase *db = [[DYDB sharedDB] connect];
	BOOL ret = [db executeUpdate:sql, logkeeper.localId];
	
	[db close];
	
	return ret;
}

- (DYLogKeeper *) findById:(NSString *)localId {
	DLog(@"find logkeeper by id: %@", localId);
	
	FMDatabase *db = [[DYDB sharedDB] connect];
	FMResultSet *rs = [db executeQuery:@"select * from log_keepers where local_id = ?", localId];

	DYLogKeeper *ret;
	
	if ([rs next]) {
		ret = rs2logkeeper(rs);
	}

	[db close];
	return ret;
}

+ (NSArray *) findOfStartDate: (NSDate *) start toDate:(NSDate *) toDate {
	DLog(@"find logkeeper between date ....");
	NSString *sql = @"select * from log_keepers where add_time between ? and ?";
	
	FMDatabase *db = [[DYDB sharedDB] connect];
	FMResultSet *rs = [db executeQuery:sql, start, toDate];
	
	NSMutableArray *array = [NSMutableArray arrayWithCapacity:32];
	while ([rs next]) {
		DYLogKeeper *logkeeper = rs2logkeeper(rs);
		[array addObject:logkeeper];
	}

	[rs close];
	[db close];
	
	return array;
}

@end
DYLogKeeper+DB.h
#import "DYLogKeeper.h"
#import <FMDB/FMDatabase.h>

DYLogKeeper * rs2logkeeper(FMResultSet *rs);

@interface DYLogKeeper (DB)

+ (void) createSqliteTable;

+ (BOOL) insert: (DYLogKeeper *) logkeeper;

+ (BOOL) updateContent: (NSString *) content localId: (NSString *) localId;

+ (BOOL) remove: (DYLogKeeper *) logkeeperId;

+ (DYLogKeeper *) findById: (NSString *) localId;

+ (NSArray *) findOfStartDate: (NSDate *) start toDate:(NSDate *) toDate;

@end
DYDB.m
#import "DYDB.h"
#define kDYDBObvName @"dyobv.sqlite"

@implementation DYDB

static DYDB *_sharedDB;

+ (DYDB *) sharedDB {
  if (!_sharedDB) {
		_sharedDB = [[DYDB alloc] init];
	}
	
	return _sharedDB;
}

- (id) init {
	self = [super init];
	if (self) {
		NSString* docsdir = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
		NSString *dbpath = [docsdir stringByAppendingPathComponent:kDYDBObvName];
		DLog(@"database file path: %@", dbpath);
		
		_database = [FMDatabase databaseWithPath:dbpath];
	}
	
	return self;
}

- (FMDatabase *) connect {
		
	if ([_database open]) {
		return _database;
	}
	
	DLog(@"fail to open db...");
	return nil;
}

- (void) clearDB {
	dispatch_async(dispatch_get_main_queue(), ^{
		if([_database close]) {
			_database = nil;
		}
	});
}

@end
DYDB.h
#import <Foundation/Foundation.h>
#import <FMDB/FMDatabase.h>

@interface DYDB : NSObject {
  
}

@property(nonatomic, readonly) FMDatabase *database;

+ (DYDB *) sharedDB;

- (FMDatabase *) connect;

- (void) clearDB;

@end

c_cpp map.cpp

map.cpp
#include <iostream>
#include <string>
#include <map> // Cabecera necesaria para usar map
 
int main()
{
  // Creamos un map de string (clave) e int (valor)
	std::map<std::string, int> m;

	m["uno"] = 1;
	m["dos"] = 2;
	m["tres"] = 3;

	std::cout << m["uno"] << std::endl;
	std::cout << m["dos"] << std::endl;
	std::cout << m["tres"] << std::endl;
}

c_cpp map.cpp

map.cpp
#include <iostream>
#include <string>
#include <map> // Cabecera necesaria para usar map
 
int main()
{
  // Creamos un map de string (clave) e int (valor)
	std::map<std::string, int> m;

	m["uno"] = 1;
	m["dos"] = 2;
	m["tres"] = 3;

	std::cout << m["uno"] << std::endl;
	std::cout << m["dos"] << std::endl;
	std::cout << m["tres"] << std::endl;
}