Guest User

Untitled

a guest
Jun 24th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
  2.  
  3. #include <stdio.h>
  4. #include <algorithm>
  5. #include <string>
  6.  
  7. using std::string;
  8.  
  9. std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
  10.  
  11.  
  12. int main() {
  13.  
  14. string* pArrEnd = arr + sizeof( arr)/sizeof(arr[0]);
  15.  
  16. string* pFound = std::find( arr, pArrEnd, "MARK");
  17.  
  18. if (pFound == pArrEnd) {
  19. printf( "not foundn");
  20. }
  21. else {
  22. printf( "%s was found at index %dn", pFound->c_str(), pFound - arr);
  23. printf( "or using STL: %dn", std::distance( arr, pFound));
  24. }
  25.  
  26. return 0;
  27. }
  28.  
  29. // alloc the array
  30. static const size_t numItems = 100000;
  31. int * items = new int[numItems];
  32.  
  33. // fill the array
  34. for( size_t n = 0; n < numItems; ++n )
  35. items[n] = n;
  36.  
  37. // find 42 using std::find()
  38. int* found = std::find(&items[0], &items[numItems], 42);
  39. if( found == &items[numItems] )
  40. {
  41. // this is one past the end, so 42 was not found
  42. items[0] = 42;
  43. }
  44. else
  45. {
  46. // we found the first instance of 42 at this location
  47. // change it to 43
  48. *found = 43;
  49. }
  50.  
  51. int main()
  52. {
  53. // for c++ vector
  54. typedef int Element;
  55. typedef std::vector<Element> CppVector;
  56.  
  57. CppVector v;
  58. v.push_back( 2 );
  59. v.push_back( 4 );
  60. v.push_back( 8 );
  61. v.push_back( 6 );
  62.  
  63. const Element el = 4;
  64.  
  65. CppVector::const_iterator it = std::find( v.begin(), v.end(), el );
  66. if ( it == v.end() )
  67. {
  68. std::cout << "there is no such element" << std::endl;
  69. }
  70. else
  71. {
  72. const CppVector::size_type index = it - v.begin();
  73. std::cout << "index = " << index << std::endl;
  74. }
  75.  
  76. // for C array
  77. typedef Element CVector[4];
  78. CVector cv;
  79. cv[0] = 2;
  80. cv[1] = 4;
  81. cv[2] = 8;
  82. cv[3] = 6;
  83.  
  84. const std::size_t cvSize = sizeof( cv ) / sizeof( Element );
  85.  
  86. std::cout << "c vector size = " << cvSize << std::endl;
  87.  
  88. const Element* cit = std::find( cv, cv + cvSize, el );
  89. const std::size_t index = cit - cv;
  90.  
  91. if ( index >= cvSize )
  92. std::cout << "there is no such element" << std::endl;
  93. else
  94. std::cout << "index = " << index << std::endl;
  95. }
Add Comment
Please, Sign In to add comment