jeudi 4 octobre 2012

How to map array into a std::vector and display value.

As C++ user, you may have to check if a given value is allow in your software and if not display the list of allowed values.

To do that job, you can write code based on C++/STL and use as few "if"s, "while"s, "for"s and other builtin constructs as possible. In the following  example, I try to demonstrate 3 things:
  1. Init a vector within a array. Note that in the new C++ standard, you can implement that with a single line.
  2. Check if a value is in the vector using the 'find' algorithm.
  3. Display on stdout or format into a string all values using 'copy'.


#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream>

int _tmain(int argc, _TCHAR* argv[])
{

  int tab[5] = {1,2,3,4,5};
  std::vector<int> test(tab, tab+5);

  int valueForChecking = -1;
  std::cin >> valueForChecking;

  if(std::find(test.begin(), test.end(), valueForChecking) == test.end())
  {  
    std::copy(test.begin(), test.end(), std::ostream_iterator<int>(std::cout," ")); 
    std::cout << std::endl;
  }
  else
    std::cout << "is in" << std::endl;

  //or

  if(std::find(test.begin(), test.end(), valueForChecking) == test.end())
  {
    std::ostringstream s;
    std::copy(test.begin(), test.end(), std::ostream_iterator<int>(s," "));
    std::cout << "string from vector : " << s.str() << std::endl;
  }
  else
    std::cout << "is in" << std::endl;

  return 0;
}

Aucun commentaire :

Enregistrer un commentaire