如何在每个元素成对成对的c ++中将向量的内容打印到屏幕
how to print the contents of the vector to screen in c++ whose each element is pair in a pair
我正在做一个作业,其中包含这种类型的向量的元素 vector<pair<string,pair<int,int> > > A
.
for(auto it=A.begin();it!=A.end();it++)
cout <<*it.first<<" "<< *it.second.first <<" "<<*it.second.second;
但显示错误。
谁能帮帮我?
你需要使用(*it).first
而不是*it.first
,因为*it.first
表示迭代器是it.first
,但实际上迭代器是(*it)
。
您可以使用 ->
来解决这个问题,例如 it->first
。因为如果你使用 ->
它比使用 *
.
容易得多
vector<pair<string,pair<int,int> > > A;
for(auto it = A.begin(); it != A.end(); it++){
//cout << (*it).first << " " << (*it).second.first << " " << (*it).second.second;
cout << it->first << " " << it->second->first << " " << it->second->second;
}
使用现代 C++ 语言功能 (C++17),这要简单得多:
for (const auto &[s, p] : A)
{
const auto &[a, b] = p;
std::cout << s << " " << a << " " << b << std::endl;
}
如果您的 C++ 教科书 and/or 编译器不涵盖 C++17,那么花时间更新您的文档 and/or 您的编译器到当前的 C++ 标准真的很值得。
您可以使用基于范围的循环而不是迭代器来避免 *
:
的问题
for(const auto& itr:A)
{
std::cout<< "Base Pair 1st: "<<itr.first<<" level pair 1st:"<<itr.second.first<<" level pair 2nd "<<itr.second.second;
}
我正在做一个作业,其中包含这种类型的向量的元素 vector<pair<string,pair<int,int> > > A
.
for(auto it=A.begin();it!=A.end();it++)
cout <<*it.first<<" "<< *it.second.first <<" "<<*it.second.second;
但显示错误。
谁能帮帮我?
你需要使用(*it).first
而不是*it.first
,因为*it.first
表示迭代器是it.first
,但实际上迭代器是(*it)
。
您可以使用 ->
来解决这个问题,例如 it->first
。因为如果你使用 ->
它比使用 *
.
vector<pair<string,pair<int,int> > > A;
for(auto it = A.begin(); it != A.end(); it++){
//cout << (*it).first << " " << (*it).second.first << " " << (*it).second.second;
cout << it->first << " " << it->second->first << " " << it->second->second;
}
使用现代 C++ 语言功能 (C++17),这要简单得多:
for (const auto &[s, p] : A)
{
const auto &[a, b] = p;
std::cout << s << " " << a << " " << b << std::endl;
}
如果您的 C++ 教科书 and/or 编译器不涵盖 C++17,那么花时间更新您的文档 and/or 您的编译器到当前的 C++ 标准真的很值得。
您可以使用基于范围的循环而不是迭代器来避免 *
:
for(const auto& itr:A)
{
std::cout<< "Base Pair 1st: "<<itr.first<<" level pair 1st:"<<itr.second.first<<" level pair 2nd "<<itr.second.second;
}