Using standard data structure

The basic data structures of the standard C++ library are available, once you have included the correct header files. Many of our constructions will be based on such containers.

If for instance, you want to manipulate lists of say integer, you will use the type: std::list<int> which is a parametrised type std::list<T> in which we instantiate the type T by int. The std prefix is here to speficy that the list implementation is from the standard library.

Let us detail what is going on the following example:

o+

#include <iostream>
#include <list>
int main()
{ 

  typedef std::list<int>::const_iterator iterator;
  std::list<int> l; 
  l.push_back(1); l.push_back(2); l.push_back(3);
  for(iterator it=l.begin(); it!=l.end(); it++) 
  std::cout<<*it<<" ";std::cout<<std::endl;

}

Once you have written this code in a file fich.cc, you can compile it with the usual compiler command

g++ -o step1.ex step1.cc

and run the executable step1.ex or use the command s++:

s++ step1.cc

which will also produce the executable fich.ex. The result of this first execution should look like this:

./step1.ex
1 2 3
If you type directly

s++ step1.cc -run

the file will be compiled and executed. For more information, on the basic data structures available in the STL, we refer to its reference manual.

Exercise: Write a function sum which takes as input a list of int and outputs the sum of its element. $\boxdot$

Exercise: Write a function apply which takes as input a list of int and a class defining int opetator()(int a, int b) (corresponding for instance to the addition) and which applies it the elements of the list. $\boxdot$

Here is an example illustrating the use of generic functions on containers \ from some modules such as VECTOR (for vectors) or UPOLDAR:

o+

#include <iostream>
#include <vector>
#include <synaps/linalg/VECTOR.m>
#include <synaps/upol/UPOLDAR.m>
typedef std::vector<int>  rep_t;
typedef rep_t::const_iterator iterator;

int main()
{ 
  rep_t l; 
  l.push_back(1); l.push_back(2); l.push_back(3);
  VECTOR::print(std::cout,l)<<std::endl;
  UPOLDAR::print(std::cout,l)<<std::endl;

}

In this example, we use the container std::vector instead of std::list, because it provides a direct access function to the $i^{\tmop{th}}$ element. The executation of this programme should give:

[1,2,3]
(3)*x0^2+(2)*x0+(1)  

SYNAPS DOCUMENTATION
logo