C++/Vector/vector back

Материал из C\C++ эксперт
Версия от 13:27, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Demonstrating the STL vector back and pop_back operations

<source lang="cpp">

  1. include <iostream>
  2. include <vector>
  3. include <string>

using namespace std; int main() {

 string s("abcdefghij");
 vector<char> vector1(s.begin(), s.end());
 while (vector1.size() > 0) {
   cout << vector1.back();
   vector1.pop_back();
 }
 cout << endl;
 return 0;

} /* jihgfedcba

*/        
 </source>


Get the last element in the vector

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <vector> // vector class-template definition
  2. include <algorithm> // copy algorithm
  3. include <iterator> // ostream_iterator iterator
  4. include <stdexcept> // out_of_range exception

int main() {

  int array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
  std::vector< int > integers( array, array + 6 );
  std::ostream_iterator< int > output( cout, " " );
  integers.push_back( 2 );
  integers.push_back( 3 );
  integers.push_back( 4 );
  cout << "Vector integers contains: ";
  std::copy( integers.begin(), integers.end(), output );
  cout << "\nLast element of integers: " << integers.back();
  return 0;

} /* Vector integers contains: 1 2 3 4 5 6 2 3 4 Last element of integers: 4

*/        
 </source>