gpt4 book ai didi

c++ - for循环的初始化语句有两种类型的变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:45 24 4
gpt4 key购买 nike

我想在 for 的 init 语句中声明两种类型的变量。像下面的代码。我知道“for (string word, int numb, ; cin>>word>>numb; )”不起作用。只是想让你知道我想做什么。我的目标是声明两种具有相同生命周期的变量并将它们放在一起。其他编码方式也很有帮助。提前致谢。

#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
cout<<"enter a word and a number"<<endl;
for (string word, int numb, ; cin>>word>>numb; )
{
//do some work
}
return 0;
}

好的,我认为这是我能得到的最接近的人的建议。

#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
vector<pair<string,int> > pvec;
cout<<"enter a word and a number"<<endl;
{
int numb=0;
for (string word; cin>>word>>numb; )
pvec.push_back(make_pair(word,numb));
}
cout<<pvec[3].second<<endl;
return 0;
}

最佳答案

你能得到的最近的大概是:

int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
for (int numb; cin>>word>>numb; )
{
//do some work
}
}
return 0;
}

这组额外的大括号限制了 word 的范围,类似于循环限制 numb 的范围的方式。显然,您可以撤销声明;使用它可能更好(更对称):

int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
int numb;
while (cin>>word>>numb)
{
//do some work
}
}
return 0;
}

由于没有递增或初始化操作,代码实际上是一个带有几个已声明变量的 while 循环;这实现了相同的结果和工作。

关于c++ - for循环的初始化语句有两种类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com