问题主要来自于:
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;
如果您想控制迭代器,请在 for 循环中使用它:
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,为了访问它的值,不要忘记使用 ->。
如果你想遍历整个向量,可以使用一个简单的循环。`
for (auto i: n)
{
std::cout << "My name is " << i.name << ", ";
std::cout << i.full_name << std::endl;
}`
附带说明,在 for 循环中使用它之前,您不需要声明“它”。
以下方法也可以:
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;
}