-1

I'm trying to manipulate a set of elements in vectors in c++.

vector <int> vectorOfValue;

vectorOfValue.push_back(1);
vectorOfValue.push_back(2);
vectorOfValue.push_back(3);
vectorOfValue.push_back(4);
vectorOfValue.push_back(5);
vectorOfValue.push_back(6);
vectorOfValue.push_back(7);
vectorOfValue.push_back(8);
vectorOfValue.push_back(9);
vectorOfValue.push_back(10);

I would like to know how the program can print out the vectors of values bigger 3 and smaller than 9.

It is a set of the data to exclude the outliers for example.

mkl
  • 90,588
  • 15
  • 125
  • 265
VictorMF
  • 19
  • 2
  • 1
    For example by using an if statement or a predicate – Vlad from Moscow Dec 18 '17 at 17:13
  • 6
    What you would like to do is very simple, Being able to do just that with help from other SO users is not going to help you in the long run. Please pick up [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn the basics of the language. – R Sahu Dec 18 '17 at 17:17
  • _I would like to know_ should read: my homework is. –  Dec 18 '17 at 17:56

2 Answers2

4

If you want to use the standard library algorithms and iterators, you could use std::copy_if:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

auto main(int argc, char* argv[]) -> int
{
  std::vector<int> vectorOfValue;
  // code for initialization of vector ..

  std::copy_if(vectorOfValue.begin(), 
               vectorOfValue.end(), 
               std::ostream_iterator<int>(std::cout, "\n"), 
               [](const int value) { return value > 3 && value < 9; });
}
Christian G
  • 943
  • 9
  • 16
  • Since the OP says *program can print out the vectors*. A simple iteration would have done. `for (vector::iterator it = vec.begin() ; it != vec.end(); ++it)if(*it>3 && *it<9)cout << *it << ' ';` Any specific reasons for `copy_if` ? Genuinely curious! – Aditi Rawat Dec 18 '17 at 17:27
  • @AditiRawat why not a range-for-loop? `for (auto value : vectorOfValue) if (value > 3 && value < 9) cout << value << ' ';` – mch Dec 18 '17 at 17:28
  • Lately I am minimizing my use of for-loops if there is an appropriate std algorithm, generally prefering the "collections-way" of doing things. You might be interested in this article: https://advancedweb.hu/2017/11/21/a_detailed_case_study_against_for/ – Christian G Dec 18 '17 at 17:30
-1

Short approach of mine using auto syntax instead of using iterator :

for(auto &i : vectorOfValue) {
   if (i > 3 && i < 9) {
      std::cout << i << std::endl;
   }
}