1

I made a function for printing a vector using interators. The function is part of program meant to copy a vector of strings to another vector of strings. The original function was a simple for loop using the .at() member function and that worked. So, I am not sure what's wrong with this one. The code:

#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(vector<string> &v);

int main() {
    ifstream inFS;
    inFS.open("sentence.txt");

    vector<string> wordList; vector<string> newVect; 
    string s;
    while (inFS >> s) {
        wordList.push_back(s);
    }

    copy(wordList.begin(), wordList.end(), newVect.begin());
    print(wordList);
    print(newVect);
}


void print(vector<string> &v) {
    for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
        cout << *i << " ";
    }
    cout << endl;
}

The output:

C:\Users\westt\Documents\PROJECT>a.exe

C:\Users\westt\Documents\PROJECT>
  • Before `copy` you need to ensure that `newVect` has enough elements. Add `newVect.resize(wordList.size());` before `copy`. – songyuanyao Sep 10 '18 at 02:33

1 Answers1

1

Try this simple change to initialize the newVect. As the comment noted, you could also resize() newVect

#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(vector<string> &v);

int main() {
    ifstream inFS;
    inFS.open("sentence.txt");

    vector<string> wordList; 
    string s;
    while (inFS >> s) {
        wordList.push_back(s);
    }

    vector<string> newVect(wordList);
    print(wordList);
    print(newVect);
}


void print(vector<string> &v) {
    for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
        cout << *i << " ";
    }
    cout << endl;
}
Matthew Fisher
  • 2,258
  • 2
  • 14
  • 23