如何在C ++中移动2个dim数组 [英] How to shift 2 dim array in C++
问题描述
hii
如何移动2个昏暗阵列
它是用于课程和成绩的数组,以及用户在程序开头输入的数组大小。
我也有一个名字的字符串数组。
如果它是4门课程将是这样的:
名称等级1等级2等级3等级4
i想要删除一行然后移动所以最后一行将为零。
i将向您显示所有移动的部分,我尝试了但是它没有工作,当我输入名称时光标没有做任何事情:
我尝试过:
hii
how can i shift 2 dim array
it's array for courses and grades , and the size of the array entered by the user at the beginning of the program.
also i have a string array for names.
it will be like this if it's 4 courses :
name grade1 grade2 grade3 grade4
i want to delete a row and then shift so the last row will be zero.
i will show you all only the part of shifting, what i have tried but it didn't work, when i enter the name the cursor goes down without doing anything :
What I have tried:
index=0;
cout<<"Enter your name :";
cin>>name;
for(int p=0;p<i;p++){
if (arn[p]==name)
index=p;}
for(int row=index;row<i;row++){
for (int colm1=0;colm1<j;colm1++)
arcg[row][colm1]=arcg[row-1][colm1-1];}
for(int colm2=0;colm2<j;colm2++)
arcg[i-1][colm2]=0;
for (int row3=0;row3<i;i++) {
if (arn[row3]==name)
arn[row3]=arn[row3+1];
arn[i-1]="0";}
for(int row=0;row<i;row++){
for (int colm1=0;colm1<j;colm1++){
cout<<arcg[row][colm1]<<"/t";
}
}
for(int colm2=0;colm2<j;colm2++){
cout<<arn[colm2]<<"/t";
}
推荐答案
你不会移动东西。创建一个新数组,将旧数组中的元素复制到新数组,跳过删除的项,销毁旧数组并返回新数组。
You don't move stuff around. Create a new array, copy the elements from the old array to the new one, skipping the items you deleted, destroy the old array and return the new array.
尝试
Try
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int index;
cout << "Enter your name :";
cin >> name;
int i=3;
int j=4;
const int ROWS=i;
const int COLS=j;
string arn[ROWS] = {"foo", "boo", "goo"};
int arcg[ROWS][COLS] = { { 0, 1, 2, 3}, {10, 11, 12, 13}, {20, 21, 22, 23}};
index = ROWS;
for(int p=0;p<ROWS;p++)
{
if (arn[p]==name)
{
index = p;
break;
}
}
// shift
for ( int row = index; row<ROWS-1; ++row)
{
arn[row] = arn[row+1];
for ( int col= 0; col < COLS; ++col)
arcg[row][col] = arcg[row+1][col];
}
// reset last row
if ( index != ROWS )
{
arn[ROWS-1] = "-";
for ( int col= 0; col < COLS; ++col)
arcg[ROWS-1][col] = 0;
}
// show the arrays
for ( int row = 0; row<ROWS; ++row)
{
cout << arn[row];
for ( int col= 0; col < COLS; ++col)
cout << "\t" << arcg[row][col];
cout << endl;
}
}
请注意, C ++
(特别是现代 C ++
)提供了更强大的工具:
Please note, C++
(expecially modern C++
) offers far more powerful tools:
#include <iostream>
#include <unordered_map>
#include <array>
using namespace std;
int main()
{
constexpr int COLS = 4;
unordered_map < string, array < int, COLS > > m;
m["foo"] = array<int,COLS>{0,1,2,3};
m["boo"] = array<int,COLS>{10,11,12,13};
m["goo"] = array<int,COLS>{20,21,22,23};
string name;
cout << "Enter your name: ";
cin >> name;
auto it = m.find(name);
if (it != m.end())
m.erase(it);
for (const auto & p : m)
{
cout << p.first;
for (const auto & i : p.second)
cout << "\t" << i;
cout << endl;
}
}
这篇关于如何在C ++中移动2个dim数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!