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上也會有這種簡單的問題)