std::copy 函数的坑

#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");

    if (!inFS) {
        perror("open");
        return -1;
    }

    vector<string> wordList, newVect;
    string s;
    while (inFS >> s) {
        wordList.push_back(s);
    }
    //newVect.resize(wordList.size());
    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;
}

无意中看到stackoverflow上的问题,才发现copy函数的实现不会去分配空间,所以需要resize以下。(原来stackoverflow上也会有这种简单的问题)

猜你喜欢

转载自blog.csdn.net/wWX336815/article/details/82588170