gpt4 book ai didi

c++ - 用不同的值填充数组/vector 的边缘和中心

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:40 25 4
gpt4 key购买 nike

我想创建一个函数来初始化大小为 width * height 的 vector 或数组,但也会在这些值周围创建一个边框。

外侧的值也需要初始化为与中心不同的值。

我存储的对象没有默认构造函数,所以我不能依赖它进行初始化。

这是我到目前为止的代码,但感觉应该有更简单或更惯用的方法来执行此操作。

我可以使用包括 C++1z 在内的任何功能。

#include <iostream>
#include <vector>

void fill_values(const unsigned width, const unsigned height, std::vector<int> &values) {
for(unsigned y=0; y<height+2; ++y) {
for(unsigned x=0; x<width+2; ++x) {
if(x==0 || x==width+1 || y==0 || y==height+1) {
values.push_back(1);
} else {
values.push_back(0);
}
}
}
}

int main(int argc, char *argv[]) {
const unsigned width = 4;
const unsigned height = 3;
std::vector<int> values;

fill_values(width, height, values);

for(unsigned y=0; y<height+2; ++y) {
for(unsigned x=0; x<width+2; ++x) {
std::cout << values[y * (width+2) + x];
}
std::cout << '\n';
}

return 0;
}

输出:-

111111
100001
100001
100001
111111

最佳答案

老实说,你的代码没问题。我很容易理解它的作用。

但本着提出替代复杂实现的精神,我提出以下建议。填充矩阵的另一种方法是添加一整行 1,然后是 height1000...001,然后是另一整行 1。我们可以让它更明确一点。此外,建议返回一个 vector 而不是填充它:

std::vector<int> fill_values(const unsigned width, const unsigned height) {
std::vector<int> m;
m.reserve((width + 2) * (height + 2));

// add row of 1s
m.insert(m.end(), width + 2, 1);

// add height middle rows
for (int i = 0; i < height; ++i) {
m.push_back(1);
m.insert(m.end(), width, 0);
m.push_back(1);
}

// and a final row of 1s
m.insert(m.end(), width + 2, 1);

return m;
}

关于c++ - 用不同的值填充数组/vector 的边缘和中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com