string_cat.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright (C) 2006 Douglas Gregor <doug.gregor@gmail.com>
  2. // Use, modification and distribution is subject to the Boost Software
  3. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // An example using Boost.MPI's reduce() to concatenate strings.
  6. #include <boost/mpi.hpp>
  7. #include <iostream>
  8. #include <string>
  9. #include <boost/serialization/string.hpp> // Important for sending strings!
  10. namespace mpi = boost::mpi;
  11. /* Defining STRING_CONCAT_COMMUTATIVE lies to Boost.MPI by forcing it
  12. * to assume that string concatenation is commutative, which it is
  13. * not. However, doing so illustrates how the results of a reduction
  14. * can change when a non-commutative operator is assumed to be
  15. * commutative.
  16. */
  17. #ifdef STRING_CONCAT_COMMUTATIVE
  18. namespace boost { namespace mpi {
  19. template<>
  20. struct is_commutative<std::plus<std::string>, std::string> : mpl::true_ { };
  21. } } // end namespace boost::mpi
  22. #endif
  23. int main(int argc, char* argv[])
  24. {
  25. mpi::environment env(argc, argv);
  26. mpi::communicator world;
  27. std::string names[10] = { "zero ", "one ", "two ", "three ", "four ",
  28. "five ", "six ", "seven ", "eight ", "nine " };
  29. std::string result;
  30. reduce(world,
  31. world.rank() < 10? names[world.rank()] : std::string("many "),
  32. result, std::plus<std::string>(), 0);
  33. if (world.rank() == 0)
  34. std::cout << "The result is " << result << std::endl;
  35. return 0;
  36. }