歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 當C++遇到iOS應用開發之---List集合

當C++遇到iOS應用開發之---List集合

日期:2017/3/1 10:07:41   编辑:Linux編程

在Object-C中,數組使用NSArray和NSMutableArray(可變長數組)。使用語法如下:

NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil];

取數組元素的方法:

[array objectAtIndex:2]);

因為數組在開發中會被頻繁使用,且objectAtIndex的寫法看著過於繁復,遠不如array[2]這種直觀。所以我將C++中的vector類進行了封裝,並增加一些新的功能:

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. using namespace std::tr1;
  5. template<typename T, typename _Alloc = std::allocator<T> >
  6. class List: public vector<T, _Alloc>
  7. {
  8. private:
  9. typedef typename std::vector<T>::iterator list_it;
  10. list_it _it;
  11. public:
  12. List(){}
  13. List(NSArray *array){
  14. copyFromArray(array);
  15. }
  16. List(string *array){
  17. copyFromArray(array);
  18. }
  19. List(int *array){
  20. copyFromArray(array);
  21. }
  22. ~List()
  23. {
  24. std::cout<<"list destroy!"<<endl;
  25. }
  26. List& add(const T t){
  27. this->push_back(t);
  28. return (*this);
  29. }
  30. void clear(){
  31. //this->clear();
  32. this->erase(this->begin(), this->end());
  33. }
  34. BOOL contains(const T t){
  35. return indexOf(t) >= 0;
  36. }
  37. int indexOf(const T t){
  38. list_it it = std::find(this->begin(),this->end() , t ) ;
  39. if(it != this->end())
  40. return it - this->begin();
  41. return -1 ;
  42. }
  43. void insert(int index, const T t)
  44. {
  45. this->insert(this.begin() + index, 1, t);
  46. }
  47. void remove(const T t)
  48. {
  49. int pos = indexOf(t);
  50. if (pos >= 0)
  51. this->removeAt(pos);
  52. }
  53. void removeAt(int index)
  54. {
  55. if (this->size() > index){
  56. this->erase(this->begin() + index, this->begin() + index + 1);
  57. }
  58. }
  59. int count()
  60. {
  61. return this->size();
  62. }
  63. void copyFrom(List<T> list)
  64. {
  65. this->assign(list.begin(), list.end());
  66. }
  67. void copyFromArray(NSArray *array){
  68. for(int i = 0; i< [array count]; i++){
  69. T t = (T)[array objectAtIndex:i];
  70. this->push_back(t);
  71. }
  72. }
  73. void copyFromArray(string* array){
  74. for(int i = 0; i< array->length(); i++){
  75. T t = (T)array[i];
  76. this->push_back(t);
  77. }
  78. }
  79. void copyFromArray(int* array){
  80. for(int i = 0; i<(sizeof(array)/sizeof(int)); i++){
  81. T t = (T)array[i];
  82. this->push_back(t);
  83. //this->vector<T>::push_back(new T);//usage:用父類方法 或 static_cast<vector<T>*>(this)->push_back(T);
  84. }
  85. }
  86. };
Copyright © Linux教程網 All Rights Reserved