【发布时间】:2018-08-12 07:06:12
【问题描述】:
#include<bits/stdc++.h>
using namespace std;
int main() {
int i,j;
vector<int> v(100); // defined a vector of size 100
for(i=1;i<=50;i++) {
v[i]=i; // storing the values as we do in 1-d array
}
for(int i=1;i<=50;i++) {
cout<<"index="<<i<<" "<<v[i]<<"\n"; // It will give output similar
// to 1-d array
}
return 0;
}
所以这是一维向量的情况,其中向量的索引是整数,值也是整数。以上代码运行良好。
但我想将向量的索引作为对 (i,j) 并将值作为整数。
请参阅下面的代码以获得更多说明。
#include<bits/stdc++.h>
using namespace std;
int main() {
int i,j;
vector<pair<int,int>> ve(make_pair(100,100));
//defined a vector of size of indices (100,100)
for(i=1;i<=50;i++) {
for(j=0;j<=50;j++) {
ve[make_pair(i,j)]=2; // Storing value of 2 in all the
// (i,j) indices
}
}
for(int i=1;i<=50;i++) {
for(j=0;j<=50;j++) {
cout<<ve[make_pair(i,j)]<<" ";
// Output should be 2 in all the possible pairs of (i,j)
}
}
return 0;
}
但是上面的代码不起作用:(。 请告诉我如何解决这个问题。
【问题讨论】:
-
您混淆了元素类型和索引类型。首先,两者都是整数类型。在第二个中,您将元素类型切换为一对,但索引类型保持不变。
-
也许您想停止使用这种
#include<bits/stdc++.h>废话并了解每个单独的标准标头的作用。其中一个或多个可能会提供您想要的设施。 OTOH 向量的向量可能正是您所需要的(ve[i][j]更容易理解并且看起来并不难看)。 -
@n.m.我对标题非常了解。因此,您只需专注于回答问题。
-
@Deepak 在固定范围内,顺序,您最好以二维形式使用 std::array。我在下面的答案中的示例。不是矢量,当然也不是地图。