简体   繁体   中英

overload << operator to work with pointer to string

I am learning to use the find method and from my knowledge it returns an iterator to the found item , this is my sample code which i am trying to find the string "foo"

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<string> foo;

    vector<string>::iterator v1;
    vector<string>::iterator v2;

    v1=foo.begin();
    v2=foo.end();

    foo.push_back("bar");
    foo.push_back("foo");



    std::vector<string>::const_iterator it = find(v1, v2, "foo");

    cout<<*it;

}

I am getting the following error when i try to compile the code

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

I am unable to cout the deference to the pointer, it seems i must overload the << operator but it is weird that i must overload the << operator to work with string as i can already do

string boo = "bar"
cout<<boo;

What is happening and how can i solve this problem ??

I am able to compile it under GCC, but MSVC rejects it. As chris's comment indicates, adding #include <string> solves the problem.

Your program then crashed when running. You assigned to v1 and v2 before your assigned the values to the vector, so the result of it never points to "foo". Moving the two assignments to below the two push_back statements should solve the problem. Still you need to check the return result of it as follows:

if (it != foo.end()) {
    cout << *it << endl;
} else {
    cout << "*** NOT FOUND" << endl;
}

Add #include <string> and you should be fine.

Also, make sure you compile with C++11 (not the default with some compiler).

Also, to be on the safe side, take v1 and v2 after you push_back the values. v1 and v2 could point to obsolete location after vector has changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM