把这段代码从C语言改为C++语言 int s1, s2, len, terminal[m*2]; char ch; for(i = 0; i < m; ++i) { scanf("%d", &s1); s1--; terminal[i*2] = s1; ch = getchar(); while(ch != '\n') { scanf("%d %d", &len, &s2); s2--; if(D[s1][s2] == -1 || D[s1][s2] > len) { D[s1][s2] = len; D[s2][s1] = D[s1][s2]; } s1 = s2; ch = getchar(); } terminal[i*2 + 1] = s1; }
时间: 2024-02-14 19:10:25 浏览: 62
在C++中,可以使用cin和cout代替scanf和printf函数。以下是将此代码转换为C++的方式:
```
int s1, s2, len, terminal[m*2];
char ch;
for(int i = 0; i < m; ++i)
{
cin >> s1;
s1--;
terminal[i*2] = s1;
ch = getchar();
while(ch != '\n')
{
cin >> len >> s2;
s2--;
if(D[s1][s2] == -1 || D[s1][s2] > len)
{
D[s1][s2] = len;
D[s2][s1] = D[s1][s2];
}
s1 = s2;
ch = getchar();
}
terminal[i*2 + 1] = s1;
}
```
请注意,由于在C++中,数组的大小必须在编译时确定,因此可以考虑使用vector代替数组。以下是使用vector的代码:
```
int s1, s2, len;
char ch;
vector<int> terminal(m*2);
for(int i = 0; i < m; ++i)
{
cin >> s1;
s1--;
terminal[i*2] = s1;
ch = getchar();
while(ch != '\n')
{
cin >> len >> s2;
s2--;
if(D[s1][s2] == -1 || D[s1][s2] > len)
{
D[s1][s2] = len;
D[s2][s1] = D[s1][s2];
}
s1 = s2;
ch = getchar();
}
terminal[i*2 + 1] = s1;
}
```
阅读全文