同时设置多个数组变量(C )
set multiple array variables at the same time (c++)
我正在尝试使用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。
相关文章:
- 将数组的地址分配给变量并删除
- 试图让变量检查数组中的某些内容
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 在C++中将变量 wstring 分配给 Char 数组
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- c++ 中的别名变量数组
- 使用类的其他成员变量定义类的成员变量数组
- 可视化 如何在C++中使用复杂变量数组
- 如何 for 循环类变量数组
- 按变量数组中的列将一组整数从文本文件读入
- 运行时C++中的变量数组维度
- C++变量数组
- 将变量(数组类型)从函数传递到"main"范围类型:标准::tr1::match_results<标准::字符串::const_iterator>
- 在堆栈上使用大变量/数组的缺点
- 如何在继承类中创建父类变量数组作为私有成员
- 如何创建一个类变量数组
- 需要以编程方式初始化类变量数组,我怎么做最好
- 直接使用变量(数组中的数据返回相同)或与指针一起使用
- 如何用模板类型初始化成员变量数组