Monday 18 June 2018

C++ STL Algorithms



bool IsOdd (int i) {
  return ((i%2)==1);
}

std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n';




it = find (myvector.begin(), myvector.end(), 30);
  if (it != myvector.end())
    std::cout << "Element found in myvector: " << *it << '\n';


---------------------
move 
Move range of elements (function template )
std::vector foo = {"air","water","fire","earth"};
  std::vector bar (4);

  // moving ranges:
  std::cout << "Moving ranges...\n";
  std::move ( foo.begin(), foo.begin()+4, bar.begin() );

-------------
replace_if
Replace values in range (function template )


for (int i=1; i<10 cite="" i="" myvector.push_back="" style="color: #007000; font-style: normal;">// 1 2 3 4 5 6 7 8 9
std::replace_if (myvector.begin(), myvector.end(), IsOdd, 0); // 0 2 0 4 0 6 0 8 0----------------------
sort
Sort elements in range (function template )


 std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33
--------------

No comments:

Post a Comment