我基本上想知道我们可以在哪个区域使用 pair STL,我们如何迭代 pair STL。这是一个简短的代码,我试图在其中迭代一对,但它给出了错误。
int main()
{
pair<int,int>a;
a=make_pair(1,22);
a=make_pair(2,33);
a=make_pair(3,44);
for(pair<int,int>::iterator i:a)
{
cout<<a.first<<"-->";
cout<<a.second;
cout<<endl;
}
}
最佳答案
只要您的数据具有键/值关系,如果还需要键,一对可能会派上用场。
一个对只能存储两个元素,因此您尝试存储三个对是行不通的。每对新的将取代旧的一对。如果您需要多对,请为您想要的对类型添加一个容器。示例:
#include <iostream>
#include <tuple>
#include <vector>
int main() {
std::vector<std::pair<int, int>> a;
a.emplace_back(1, 22);
a.emplace_back(2, 33);
a.emplace_back(3, 44);
for(auto [First, Second] : a) {
std::cout << First
<< "-->"
<< Second
<< "\n";
}
}
how can we iterate over pair
你不能。如果你需要将 pair 中的值传递给一个以可迭代的东西作为参数的函数,你需要手动完成,比如:
for(auto p : a) { // a is a std::vector<std::pair<int, int>>
for(auto value : {p.first, p.second}) {
std::cout << value << "\n";
}
}
关于c++ - c++ 中的 pair class STL 有什么用,它像数据类型还是容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260029/