C++/Vector/object vector

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Call member function for each element in vector

  
 
/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
//#define mem_fun1 mem_fun
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>

class Person {
  private:
    std::string name;
  public:
    //...
    void print () const {
        std::cout << name << std::endl;
    }
    void printWithPrefix (std::string prefix) const {
        std::cout << prefix << name << std::endl;
    }
};
void foo (const std::vector<Person>& coll)
{
    using std::for_each;
    using std::bind2nd;
    using std::mem_fun_ref;
    // call member function print() for each element
    for_each (coll.begin(), coll.end(), mem_fun_ref(&Person::print));
    // call member function printWithPrefix() for each element
    // - "person: " is passed as an argument to the member function
    for_each (coll.begin(), coll.end(),bind2nd(mem_fun_ref(&Person::printWithPrefix),"person: "));
}

void ptrfoo (const std::vector<Person*>& coll)
                                   // ^^^ pointer !
{
    using std::for_each;
    using std::bind2nd;
    using std::mem_fun;
    // call member function print() for each referred object
    for_each (coll.begin(), coll.end(),
              mem_fun(&Person::print));
    // call member function printWithPrefix() for each referred object
    // - "person: " is passed as an argument to the member function
    for_each (coll.begin(), coll.end(),bind2nd(mem_fun(&Person::printWithPrefix),"person: "));
}

int main()
{
    std::vector<Person> coll(5);
    foo(coll);
    std::vector<Person*> coll2;
    coll2.push_back(new Person);
    ptrfoo(coll2);
}
  /* 


person:
person:
person:
person:
person:
person:
 */


Getting a C-Style Array from a Vector

  
#include <numeric>
#include <vector>
#include <iostream>
using namespace std;
template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}
void doubler( int a[], int length ){
   for( int i = 0; i < length; ++i )
      a[i] *= 2;
} 
int main( ){
   vector<int> data( 5, 1 );
   partial_sum( data.begin(), data.end(), data.begin() );
   print( data );
   if( !data.empty() ) {
      doubler( &data[0], static_cast<int>( data.size() ) );
      print( data );
   }
}


Sort vector of user-defined values

  
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <utility>
using namespace std;
typedef pair<int,string> Pair;
inline bool less_than_second( const Pair& b1, const Pair& b2 ){
   return b1.second < b2.second;
}
int main( )
{
   const char* names[] = { "A","B", "C", "D","E" };
   const int values[] = { 18, 20, 26, 30, 41 };
   const int num_pairs = sizeof( names ) / sizeof( names[0] );
   vector<Pair> pair( num_pairs );
   transform( values, values+num_pairs, names,pair.begin(), make_pair<int,string> );
   sort( pair.begin(), pair.end() );
   vector<Pair>::const_reverse_iterator pair_rend = pair.rend();
   
   for( vector<Pair>::const_reverse_iterator i= pair.rbegin(); i != pair_rend; ++i )
      cout << i->first << " - " << i->second;
   sort( pair.begin(), pair.end(), less_than_second );
   vector<Pair>::const_iterator pair_end = pair.end();
   for( vector<Pair>::const_iterator i = pair.begin();
      i != pair_end; ++i )
   cout << i->second << " - $" << i->first << " values\n";
}


Store user-defined objects in a vector.

  
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

class Employee {
  string name;
  unsigned number;
public:
  Employee() { name = ""; number = 0; }
  Employee(string n, unsigned num) {
    name = n;
    number = num;
  }
  string get_name() { return name; }
  unsigned get_number() { return number; }
};
void show(vector<Employee> vect) {
  vector<Employee>::iterator itr;
  for(itr=vect.begin(); itr != vect.end(); ++itr)
    cout << itr->get_number() << " " << itr->get_name() << endl;;
}
int main()
{
  vector<Employee> employeeList;
  employeeList.push_back(Employee("A", 9));
  employeeList.push_back(Employee("B", 8));
  employeeList.push_back(Employee("C", 6));
  employeeList.push_back(Employee("D", 1));
  show(employeeList);
  return 0;
}