C++/Vector/vector definition

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

Storing Specific Values in an Existing Container

  
#include <string>
#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;
   }
}
int main( )
{
   const char* s[] = { "A", "B", "C", "D", "Don"t know" };
   vector<string> answers( s, s+ sizeof( s ) / sizeof( s[0] ) );
   print( answers ); 
   const char* s1[] = { "A", "C", "B","D", "V", "O" };
   answers.assign( s1, s1 + sizeof( s1 ) / sizeof( s1[0] ) );
   print( answers );
}


vector declaration

  
 
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;
#include <vector>
using std::vector;
int main()
{
   vector< int > integers1( 7 ); // 7-element vector< int >
   vector< int > integers2( 10 ); // 10-element vector< int >
   size_t i;
   
   cout << integers1.size() << endl;
   for ( i = 0; i < integers1.size(); i++ ){
      cout << integers1[ i ];
   }
   cout << integers2.size() << endl;
   for ( i = 0; i < integers2.size(); i++ ){
      cout << integers2[ i ];
   }
   for ( size_t i = 0; i < integers1.size(); i++ )
      integers1[ i ] = i;
   for ( size_t i = 0; i < integers2.size(); i++ )
      integers2[ i ] = i;
   for ( i = 0; i < integers1.size(); i++ ){
      cout << integers1[ i ];
   }
   for ( i = 0; i < integers2.size(); i++ ){
      cout << integers2[ i ];
   }

   return 0;
}
/* 
7
000000010
000000000001234560123456789
 */


vector"s copy constructor

  
 
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;
#include <vector>
using std::vector;
int main()
{
   vector< int > integers1( 7 ); // 7-element vector< int >
   vector< int > integers2( 10 ); // 10-element vector< int >
   size_t i;
   
   for ( i = 0; i < integers1.size(); i++ ){
      cout << integers1[ i ];
   }
   for ( i = 0; i < integers2.size(); i++ ){
      cout << integers2[ i ];
   }
   vector< int > integers3( integers1 ); // copy constructor
   cout << integers3.size() << endl;
   for ( i = 0; i < integers3.size(); i++ ){
      cout << integers3[ i ];
   }
   return 0;
}
/* 
000000000000000007
0000000
 */