C++/Vector/vector indexer

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

Fill in vector with array by using pointer and offset

  
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
  int elems[] = {5, 6, 9, 8, 8, 3};
  vector<int> myVector(elems, elems + 6); 
  return (0);
}


make the index of the maximum

   
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main( )
{
   vector<int> v( 10, 66 );
   v[1] = 100;
   vector<int>::iterator before_itr = max_element( v.begin(), v.end() );
   cout << "The maximum before resizing is " << *before_itr;
   vector<int>::difference_type max_index = before_itr - v.begin();
}


Use indexer to update element in the vector

   
 
#include <iostream>
using std::cout;
using std::endl;
#include <vector>    
#include <algorithm> 
#include <iterator>  
#include <stdexcept> 
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 );
   integers[ 0 ] = 7; // set first element to 7
   cout << "\n\nVector integers contains: ";
   std::copy( integers.begin(), integers.end(), output );
   return 0;
}
/* 
Vector integers contains: 1 2 3 4 5 6 2 3 4
Vector integers contains: 7 2 3 4 5 6 2 3 4 
 */


Use toupper function to convert all elements in a char vector to upper case

   
 
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
int main()
{
  vector<char> v(10); // create a vector of length 10
  cout << "Size = " << v.size() << endl;
  for(int i=0; i<10; i++) 
     v[i] = i + "a";
  cout << "Current Contents:\n";
  for(int i=0; i<v.size(); i++) cout << v[i] << " ";
  cout << "\n\n";
  
  for(int i=0; i<v.size(); i++) 
     v[i] = toupper(v[i]);
  cout << "Modified Contents:\n";
  for(int i=0; i<v.size(); i++) 
     cout << v[i] << " ";
  cout << endl;
  return 0;
}
/* 
Size = 10
Current Contents:
a b c d e f g h i j
Modified Contents:
A B C D E F G H I J
 */