Tetramputechture
Tetramputechture

Reputation: 2921

Making a vector element into a string for comparison?

I'm kind of confused with vectors in C++; this is my first time using them. I made a vector of strings, and I am trying to compare elements in that vector against a letter.

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

/* Head ends here */
void displayPathtoPrincess(int n, vector <string> grid){
    for(vector<string>::iterator it = grid.begin(); it != grid.end(); ++it) {
        if(*it.strcompare('p') != 0)
            cout << 'Princess found!';
    }
}

/* Tail starts here */
int main() {

    int m;
    vector <string> grid;

    cin >> m;

    for(int i=0; i<m; i++) {
        string s; cin >> s;
        grid.push_back(s);
    }

    displayPathtoPrincess(m,grid);

    return 0;
}

Why won't this work? Won't *it always be a string type?

Here is my error:

error: 'std::vector >::iterator' has no member named 'strcompare' 

Upvotes: 0

Views: 350

Answers (3)

juanchopanza
juanchopanza

Reputation: 227608

First, in this context, . binds tighter than *, so this

*it.strcompare('p')

is equivalent to

*(it.strcompare('p'))

so you should call something like

it->methodName(args)

Second, you need to call a method of std::string, presumably std::string::compare.

Note that if all you want to do is search for an entry equal to "p", then all you have to do is

auto it = std::find(grid.begin(), grid.end(), "p");
if (it != v.end()) std::cout << "Princess found!" << std::endl;

Upvotes: 1

John Dibling
John Dibling

Reputation: 101506

There is no strcompare in the Standard Library.

Perhaps you meant compare?

Also, yes *it will be a string -- but 'p' is not. That is a char. You need to either convert 'p' to a string (eg string s(1,'p')) or compare the first (or last) character in *it to 'p' (eg (*it)[0] == 'p' -- warning, unsafe as is)

Finally, others have already mentioned this, but *it.strcompare would not bind as (*it).strcompare, but rather as *(it.strcompare). Meaning, you are trying to call a method called strcompare on the iterator, rather than what the iterator refers to. Even if string had a method called strcompare (which it doesn't), your code still wouldn't compile.

Upvotes: 0

Sqeaky
Sqeaky

Reputation: 1936

The class std::string is basic_string ( http://en.cppreference.com/w/cpp/string/basic_string ) and I do not think this class has a standard strcompare member function(Though some compilers do provide one).

I think you are trying to do something like:

if(*it == String("P"))

Which can more simply be written as:

if(*it == "P")

for an example: http://ideone.com/isa9Il

Upvotes: 0

Related Questions