Ошибка компиляции c ++: неожиданное имя типа 'string': ожидаемое выражение - PullRequest
0 голосов
/ 09 октября 2018

Я хочу использовать c ++ stl list и использовать итератор для печати всех элементов.Вот код:

#include<list>
#include<algorithm>
#include<string>
using namespace std;
int main(int argc, char* argv[]){
        list<string> list;
        //list<double> list_double(6);
        //list<int> list_int(6, 0);
        //list<double> list_double2(6, 0,0);
        //list<int> else_list(list_int);
        //list<double> iter(list_double.begin(), list_double.end());
        list.push_front("1 jack");
        list.push_front("2 jackson");
        list.push_front("3 sally");

        list<string>::iterator itrr;
        for (itrr = list.begin(); itrr!= list.end(); itrr++){
                string temp = *itrr;
                print(temp)nt main(int argc, char* argv[]){
        list<string> list;
        //list<double> list_double(6);
        //list<int> list_int(6, 0);
        //list<double> list_double2(6, 0,0);
        //list<int> else_list(list_int);
        //list<double> iter(list_double.begin(), list_double.end());
        list.push_front("1 jack");
        list.push_front("2 jackson");
        list.push_front("3 sally");

        list<string>::iterator itrr;
        for (itrr = list.begin(); itrr!= list.end(); itrr++){
                string temp = *itrr;
                print(temp);
        }
        return 0;
}


        }
        return 0;
}

, и когда я пытался скомпилировать его, он показывает некоторые ошибки:

list.cpp:17:7: error: unexpected type name 'string': expected expression
        list<string>::iterator itrr;
             ^
list.cpp:17:16: error: cannot refer to class template 'iterator' without a template argument list
        list<string>::iterator itrr;
                    ~~^
/Library/Developer/CommandLineTools/usr/include/c++/v1/iterator:522:29: note: template is declared here
struct _LIBCPP_TEMPLATE_VIS iterator
                            ^
list.cpp:18:7: error: use of undeclared identifier 'itrr'
        for (itrr = list.begin(); itrr!= list.end(); itrr++){
             ^
list.cpp:18:28: error: use of undeclared identifier 'itrr'
        for (itrr = list.begin(); itrr!= list.end(); itrr++){
                                  ^
list.cpp:18:47: error: use of undeclared identifier 'itrr'
        for (itrr = list.begin(); itrr!= list.end(); itrr++){
                                                     ^
list.cpp:19:18: error: use of undeclared identifier 'itrr'
                string temp = *itrr;
                               ^

так что же не так?Спасибо!

1 Ответ

0 голосов
/ 09 октября 2018

Проблема

list<string> list;

определяет идентификатор list как переменную типа list<string>.Это заменяет предыдущее определение идентификатора list как класса стандартной библиотеки std::list.Это означает, что когда компилятор достигает list<string> во многих более поздних точках кода, list<string> не имеет смысла.<string> не соответствует тому, что вы можете сделать с переменной.

Решение

Будьте внимательны при использовании идентификаторов.Создание list с именем list вызывает путаницу как у читателей, так и у компиляторов, так что не делайте этого.Дайте переменной другое имя.Он полон имен, так почему бы и нет namelist?

Эта проблема связана с опасностями using namespace std;.Подробнее об этом читайте Почему «использование пространства имен std» считается плохой практикой?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...