首页 > 解决方案 > 如何使 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 . . .

它不会输出我的第二个向量,即使它成功了。请帮我理解

标签: c++vector

解决方案


去一个std::vectorstd::pair<double, double>然后你的代码会变得更简单。第一个doubleTemperature,第二个是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;
    }
}

推荐阅读