Search code examples
c++visual-studiovisual-c++vectorreverse-iterator

C++ reverse_iterator error


I am trying to use a reverse_iterator for my vector and apparently this line of code is causing 3 errors.

#include <iostream>    
#include <vector>
using namespace std;
vector<string> list={};
vector<string> reverse_iterator rit = list.rbegin();

Errors:

  1. Expected a ';'
  2. Error C2146 syntax error: missing ';' before identifier 'rit'
  3. Error C2065 'rit': undeclared identifier

I am using Visual Studio 2015 Console Application.


Solution

  • you should define your vector variable first :

    std::vector<string> mylist (5);
    

    then use a reverse_iterator for it :

    std::vector<string>::reverse_iterator rit = mylist.rbegin();
    

    update:

    if you put using namespace std; then when you compile your code

    you will find that the problem with list={}

    because list is reserved class in namespace std so you can't use it as variable name when you define vector.

    to solve the problem you can simply give it another name like mylist.

    Another way:

    if you don't put using namespace std;

    no problem with declaring your vector as list

    you can do it in this way and it will compile and work as you expected:

      std::vector<std::string> list={};
      std::vector<std::string>::reverse_iterator rit = list.rbegin(); 
    

    I hope this will help you solve your error.