c++ - Merging two sorted vectors in one sorted vector -
background: general goal take 2 sorted files strings separated white space, , bring them in 1 sorted file.
current goal, see if can use merge function or similar function combine 2 sorted vectors.
i using http://www.cplusplus.com/reference/algorithm/merge/, guide use of function merge. however, error "no matching function call 'merge'".
i'm not sure if merge function wanting strings, trying use see if does.
#include <iostream> #include <fstream> #include <vector> #include <algorithm> // std::merge, std::sort #include <string> using namespace std; ifstream r_data_file(const string oname) { ifstream ist {oname}; if (!ist) { string error = "cannot open " + oname; throw runtime_error(error); } return ist; } void get_words(ifstream& ist, vector<string>& po) { (string p; ist >> p;) { po.push_back(p); } } int main () { vector<string> file1; vector<string> file2; ifstream ist = r_data_file("wordlist_1.txt"); get_words(ist, file1); ifstream ist_2 = r_data_file("wordlist_2.txt"); get_words(ist_2, file2); vector<string> file_1n2(file1.size()+file2.size()); merge(file1, file1.end(), file2, file2.end(), file_1n2); }
i appreciate thoughts, cheers!
you cannot use file1, file2 , file_1n2 simple pointers(maybe confusion comes because use plain arrays in way). here merge uses stl iterators, not pointer. fix problem, use:
merge(file1.begin(), file1.end(), file2.begin(), file2.end(), file_1n2.begin());
Comments
Post a Comment