c++ - 如何使 2D 矢量中的每个矢量不同?
问题描述
大家晚上好,我正在尝试获取一个向量向量来存储一个值表,其中第二列使用第一列的数字来计算它,而且它不起作用。我希望它存储我的值,例如:
T R
0 | 20 [R1]
1 | 30 [R2]
2 | 40 [R3]
3 | 50 [R4]
4 | 60 [R5]
[Continues until hits last number]
The numbers along the left side are the rows like Stuff[0][T] = 20, etc
So T would be vector<double>Temp and R would be vector<double>Resistance and
they are both contained in vector<vector<double> >Stuff.
因此,R 向量将使用 T 的值来计算电阻。
int main ()
{
double InitTemp,FinTemp,TempIncr;
vector <vector <double> > Stuff;
cout << "What is the range of temperatures being tested?(Initial Final) ";
cin >> InitTemp >> FinTemp;
cout << "How much would you like each temperature to increment? ";
cin >> TempIncr;
for(int i = 0; i < 2; i++)
{
vector <double> Temp;
vector<double> Resistance;
if(i == 0)
{
for (int j = InitTemp; j <= FinTemp; j+=TempIncr)
Temp.push_back(j);
Stuff.push_back(Temp);
}
if(i == 1)
{
double R=0;
for(int k = 0; k < Temp.size();k++)
{
R = Temp[k]+1;
Resistance.push_back(R);
}
Stuff.push_back(Resistance);
}
for (int i = 0; i< Stuff.size(); i++)
{
for(int j = 0; j < Stuff[i].size(); j++)
cout << Stuff[i][j] << " ";
cout << endl;
}
这段程序将进入另一个更大的程序,该程序使用函数来计算电阻,但我仍然需要使用 Temp 来执行此操作,这就是为什么我将它添加到 temp 作为占位符。我的输出如下所示:
What is the range of temperatures being tested?(Initial Final) 20 200
How much would you like each temperature to increment? 10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
Press any key to continue . . .
它不会输出我的第二个向量,即使它成功了。请帮我理解
解决方案
去一个std::vector
。std::pair<double, double>
然后你的代码会变得更简单。第一个double
是Temperature
,第二个是Resistance
。从我在您的代码中看到的内容来看,Resistance
仅将 1 添加到Temperature
. 在这种情况下,以下代码应该可以工作:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
double InitTemp, FinTemp, TempIncr;
vector <pair<double, double > > Stuff;
cout << "What is the range of temperatures being tested?(Initial Final) ";
cin >> InitTemp >> FinTemp;
cout << "How much would you like each temperature to increment? ";
cin >> TempIncr;
for (int j = InitTemp; j <= FinTemp; j += TempIncr)
Stuff.emplace_back(j, j+1);
for (int i = 0; i < Stuff.size(); i++)
{
cout << Stuff[i].first << ", " << Stuff[i].second << endl;
}
}
推荐阅读
- vue.js - Vuejs 问题;如何绑定添加到 DOM 的新元素?
- java - 不能为 HashMap 中的每一个
- linux - 查找已编译的可执行文件的版本
- c# - 有人可以解释什么是外键,以及为什么使用它吗?
- java - Java:从当前 src 目录读取图像
- javascript - 粒子生成太快 - Phaser 3
- dns - dig NS 和 nslookup 提供过时的名称服务器;+trace 或 whois 是正确的
- pyspark - Pyspark,EOFError - 内存问题或损坏的数据?
- ios - iOS 推送通知横幅清除操作按钮
- javascript - 如何将深层嵌套对象文字转换为对象数组?