C++/Vector/vector begin end

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

Assign elements in vector a value through an iterator

#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
int main()
{
  vector<char> v(10); // create a vector of length 10
  vector<char>::iterator p; // create an iterator
  int i;
  // assign elements in vector a value
  p = v.begin();
  i = 0;
  while(p != v.end()) {
    *p = i + "a";
    p++;
    i++;
  }

  return 0;
}


Vector Basic: begin(), pop_back(), push_back()

#include <iostream>
#include <vector>
using namespace std;
void print( vector<int> );
int main()
{
    vector<int> vec;
    vec.push_back( 3 );
    vec.push_back( 2 );
    print( vec );
    vector<int>::iterator p;
    p = vec.begin();
    *p = 6;
    *(p + 1) = 9;
    print( vec );
    vec.pop_back();
    print( vec );
    vec.push_back(11);
    vec.push_back(13);
    int i = 0;
    while ( i < vec.size() )
        cout << vec[i++] << "  ";
    cout << endl;
    vec[0] = 10;
    vec[1] = 11;
    vec[2] = 12;
    print( vec );
    return 0;
}
void print( vector<int> v ) {
    cout << "\nvector size is: " << v.size() << endl;
    vector<int>::iterator p = v.begin();
    while ( p != v.end() )
        cout << *p++ << "  ";
    cout << endl << endl;
}