-3
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;

int main()
{
    vector<string> test;
    test.push_back("yasir");
    test.push_back("javed"); 

    for(int i=0; i!=test.end();i++)
    {
        cout << test[i];
    }
}

Why is this code giving up an error? I am unable to identify the cause of the error. Error: No Match for operator !=....

  • 4
    Please pick up a [good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn the difference between vector *indexes* and *iterators*. – Some programmer dude May 24 '17 at 09:37
  • In your case simply do: `for(const std::string& s : test) { std::cout << s << std::endl; }`. And once done, please read up:https://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterators.html – MABVT May 24 '17 at 09:40
  • @MABVT , It Works.Thankyou for the reference of the site too – Muhammad Yasir Javed May 24 '17 at 09:41
  • 1
    Also, `std::string` is defined in the header ``, not `` or `` (which are for C-style strings). – Bo Persson May 24 '17 at 09:42
  • You are iterating wrongly. Change vector::iterator i = test.begin(). Also since you are iterating, the cout line should be: cout << *i; – Veliko May 24 '17 at 09:53

2 Answers2

2

First of all, you are trying to compare int with the iterator of vector.

for(int i=0; i!=test.end();i++)
{
    cout << test[i];
}

Here, the test.end() returns the iterator. There is no overloaded operator!= which can compare integer (int i = 0) with that iterator (test.end()).

So your loop should look more like:

for (std::vector<string>::iterator i = test.begin(); i != test.end(); i++)
{
    cout << *i;
}

You can replace std::vector<string>::iterator with auto, if using C++11 or newer.

The next thing, you included <string.h> which contains old functions such as: strlen, strcpy. Similarly, <cstring> contains C-style strings.

If you want to you use operator<<, so if you want to write:cout << then you have to do: #include <string>.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
eXpl0it3R
  • 90
  • 2
  • 6
0

As already mentioned, the problem is, that you try to compare an integer with an iterator in the "middle" of your for statement. Try this instead, it's more intuitive from my point of view

#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;

    int main()
    {
        vector<string> test;
        test.push_back("yasir");
        test.push_back("javed"); 

        for(int i=0; i<test.size();++i)
        {
            cout << test[i];
        }
    }