同时设置多个数组变量(C )

set multiple array variables at the same time (c++)

本文关键字:变量 数组 设置      更新时间:2023-10-16

我正在尝试使用C 制作ASCII艺术,并且在数组中遇到一些问题。

有什么方法可以同时设置多个数组变量?

让我更具体。

当您初始化数组时,您可以这样做。

int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

按照上面显示的方式,您可以同时设置10个数组变量。

但是,我想(重新)设置一些类似的数组变量?

a[1] = 3;
a[4] = 2;
a[5] = 2;
a[7] = 2;

由于在变量中没有规则,所以我不能做

for(int i=0; i<10; i++) a[i] = i+1;
fill(n);

我不能使用语句或填充,fill_n 函数,因为没有规律性。

总结,有什么方法可以同时设置超过1个数组变量?(就像上面的第二个代码snipplet?

给定索引值映射列表,然后一个一个分配。

template<typename T, size_t N>
void Update(T(&arr)[N], const std::vector<std::pair<size_t, T>>& mappings)
{
    for (const auto& mapping : mappings) 
        if(mapping.first < N)
            arr[mapping.first] = arr[mapping.second];
}
int main()
{
    int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Update(arr, { {1, 3}, {4, 2}, {5, 2}, {7, 2} });
    return 0;
}

据我所知,如果没有模式,控制结构是多余的,您可能会从文件中读取您。

// for user input
    int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
    for (int i = 0; i < 10; i++) {
        cout << "Please input your value for array index " << i << endl;
        cin >> arr[i];
    }
    // for manual input in initalization
    int arr[10] = { 0, 3, 2, 2, 2, 5, 6, 7, 8, 9 };

但是,更好的方法可能是从文件中读取它,http://www.cplusplus.com/forum/general/58945/读取" themassivechiphipmunk"的帖子,以确切地处理。

假设您知道要预先更改哪些索引,则可以使用单独的索引数组:

int ind[4]= {1,4,5,7};

..和一个带有值的随附数组

int new_val[4] = {3,2,2,2};

您可以使用以下for循环来分配值:

for (int i=0; i<4; i++)
    arr[ind[i]] = new_val[i];

您还应该使用一些变量,表示要更改的索引数,例如int val_num = 4而不是普通数字4。

在运行时定义为数组定义的更改可以通过使用列表来保存代表您要进行的更改的元组来轻松实现。例如,我们可以写:

 #include <tuple>                                                                
 #include <list>                                                                 
 #include <iostream>                                                             
 using namespace std;                                                            
 typedef tuple <int, int> Change;                                                
 int main() {                                                                    
     int a[5] = {1,2,3,4,5};                                                     
     list<Change> changes;                                                       
     //represents changing the 2-th entry to 8.                                  
     Change change(2,8);                                                         
     changes.push_back(change);
     for(auto current_change: changes)                                           
         a[get<0>(current_change)] = get<1>(current_change);                                     
     cout << a[2] << 'n';                                                       
 }  

打印8。