C ++ Используйте методы вектора со структурой - PullRequest
0 голосов
/ 21 апреля 2020

Я бы хотел сделать что-то подобное. можешь помочь мне :) Спасибо

/* Example: */

struct Name
{
 const char *full_name;
 const char *name;
};

std::vector<Name> n = { {"Harry Potter", "Harry"}, {"Hermione Granger", "Hermione"} };

// The expressions below does not work

string::const_iterator b = n.begin();
string::const_iterator e = n.end();
int s = n.size();
// ...

1 Ответ

0 голосов
/ 21 апреля 2020

Проблема в основном возникает из:

 string::const_iterator b = n.begin(); // not possible
 string::const_iterator e = n.end(); // not possible
 int s = n.size(); // working as intended if you print it to the console

Если вы хотите объявить итератор, в этом случае вы можете сделать:

std::vector<Name>::const_iterator it;

Если вы хотели бы иметь управляйте с помощью итератора, используйте его в a для l oop:

for (it = n.begin(); it != n.end() - 1; it++) // Will stop at the first name in our example
{
    std::cout << it->full_name << std::endl;
}

Поскольку он указывает на n, для доступа к его значениям не забудьте использовать ->.

Если вы хотите выполнить итерацию по всему вектору, можно использовать простой l oop .`

for (auto i: n)
    {
        std::cout << "My name is " << i.name << ", ";
        std::cout << i.full_name << std::endl;
    }`

В примечании к стороне, вам не нужно было объявлять «это» перед это использовалось в течение l oop. Следующее также будет работать:

for (auto it = n.begin(); it != n.end() - 1; it++) // Will stop at the first name in our example 
{
    std::cout << it->full_name << std::endl;
}

Для справки, вот мой окончательный код с примерами, я надеюсь, что это решит вашу проблему:

  struct Name
{
     std::string full_name;
     std::string name;
};


int main()
{
     std::vector<Name> n = { {"Harry Potter", "Harry"}, {"Hermione Granger", "Hermione"} }; 

     std::vector<Name>::const_iterator it;
    for (auto i : n) // Printing the whole vector
    {
        std::cout << "My name is " << i.name << ", ";
        std::cout << i.full_name << std::endl;
    }

    for (it = n.begin(); it != n.end() - 1; it++) // will return all the names except the last
    {
        std::cout << it->full_name << std::endl;

    }

    for (auto g = n.begin(); g != n.end() - 1; g++) // same as it, iterator initialized in the loop
    {
        std::cout << g->full_name << std::endl;
    }

    return 0;
}
...