phoffric
asked on
c++ std::mismatch problem with vector<string>
ref: std::mismatch
http://www.cplusplus.com/reference/algorithm/mismatch/?kw=mismatch
In this reference is sample code that uses std::vector<int>. When I modify the program to use std::vector<std::string>, the mismatch() returns two bad pointers in the pair. I added a std::equal() and it appears to work correctly. I also modified the sample program for set_intersection to use std::vector<std::string>, and it worked ok.
http://www.cplusplus.com/reference/algorithm/set_intersection/
How do you fix this program using std::mismatch? I am actually using std::set<std::string> so I don't need to sort it. (I would like to keep this in the non-C++11 domain as the OS is older and does not support this.)
http://www.cplusplus.com/reference/algorithm/mismatch/?kw=mismatch
In this reference is sample code that uses std::vector<int>. When I modify the program to use std::vector<std::string>, the mismatch() returns two bad pointers in the pair. I added a std::equal() and it appears to work correctly. I also modified the sample program for set_intersection to use std::vector<std::string>, and it worked ok.
http://www.cplusplus.com/reference/algorithm/set_intersection/
How do you fix this program using std::mismatch? I am actually using std::set<std::string> so I don't need to sort it. (I would like to keep this in the non-C++11 domain as the OS is older and does not support this.)
// mismatch algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::mismatch
#include <vector> // std::vector
#include <string>
#include <utility> // std::pair
bool mypredicate (std::string i, std::string j) {
return (i==j);
}
int main () {
bool isSame=false;
std::string myStrs[] = {"10","20","80","320","1024"}; // myStrs: 10 20 80 320 1024
std::vector<std::string> myvector(myStrs, myStrs + 5);
std::vector<std::string> myvector1(myvector.begin(), myvector.end());
// std::equal works, but std::mismatch returns bad pointers
isSame = std::equal(myvector.begin(), myvector.end(), myvector1.begin());
std::pair< std::vector<std::string>::iterator,std::vector<std::string>::iterator> mypair;
mypair = std::mismatch (myvector.begin(), myvector.end(), myvector1.begin());
std::cout << "First mismatching elements: " << *mypair.first;
std::cout << " and " << *mypair.second << '\n';
++mypair.first; ++mypair.second;
// using predicate comparison:
mypair = std::mismatch (myvector.begin(), myvector.end(), myvector1.begin(), mypredicate);
std::cout << "Second mismatching elements: " << *mypair.first;
std::cout << " and " << *mypair.second << '\n';
return 0;
}
ASKER
UPDATE #2: Got intersection program in my previous post to work by making line 12 std::vector<std::string> v(10);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Open in new window