Vectors Intro

Strings continued and Vectors introduction

Replace substring

#include <iostream>
using namespace std;

//this program will replace a substring in a user input string
//this one works when the new string has the old string in it

int main(){
    string s;
    string ow;
    string nw;
    cout << "Enter a sentence: ";
    getline(cin, s);
    cout << "Enter a word to delete: ";
    getline(cin, ow);
    cout << "Enter another word which replaces the deleted word: ";
    getline(cin, nw);
    size_t pos(0);

    while ( (pos = s.find(ow, pos)) != string::npos )
    {  
       s.replace( pos, ow.size(), nw);
       pos = pos + nw.size();
    }
    cout << s << endl;
    return 0;
}

Vector initialization

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

void printvec(const vector <int> v){
        unsigned int x;
        for  (x = 0; x < v.size(); ++x)
                cout << v.at(x) << " ";
                //cout << v[x] << " ";
        cout << endl;
}

void printvec11(const vector <int> v){
        for (auto i: v) //new c++11
                cout << i << " ";
        cout << endl;
}

void printusingiterators (vector <int> v){
        //vector <int>::iterator it;
        //using auto is simpler as it infers the data type  
        for (auto it = v.begin() ; it != v.end(); it++)
        {
                cout << ' ' << *it;
        }
        cout << '\n';
}

int main(){

        //no allocation or initialization
        vector <int> v; //declare v but with no size
        //v.at(0) =9; //throws out of bounds error
        //v[0] =9;      //throws seg fault
        v.push_back(3);
        v.push_back(4);
        v.push_back(5);

        //allocation only, no initialization
        vector <int> y(3); //create the vector y with a size of 3 (0,1,2) BUT no initialization
        cout << y.at(0) << endl; //this is not an error however pre existing data in memory may exist
        y.at(0) = 0;
        y.at(1) = 5;
        y[2] = 10;

        //allocation and initialization (all have same value)
        vector <int> z(3,1); //create the vector y with a size of 3 (0,1,2) and initialize all to 1
        // therefore z[0] z[1] z[2] all are 1

        vector <int> w = {1,2,3};  //c++11 initialization list

        printvec(v);
        printvec(y);
        printvec(z);
        printvec11(w);

        return 0;
}