-3
私の大きなプロジェクトの1つでは、ポインターを介してベクトルの要素を更新する問題を発見しました。私は私の問題のより簡単なデモンストレーションを作成しました。ポインタを介してベクトルの要素を更新する
#include <iostream>
#include <vector>
const int LOOKUP = 3;
struct Box {
int use;
int cap;
};
void print_vec(std::vector<Box>* bx) {
for (Box &b : *bx) {
std::cout << "Box: " << b.use << "/" << b.cap << std::endl;
};
}
void find_box(std::vector<Box>* bx, Box** bptr) {
for (Box &b : *bx) {
if (b.use == LOOKUP) {
*bptr = &b;
return;
}
}
}
int main() {
std::vector<Box> boxes = { {1,1}, {2,2}, {3,3}, {4,4}, {5,5} };
std::vector<Box>* bx = &boxes;
Box** bptr = new Box *;
Box b;
print_vec(bx);
find_box(bx, bptr);
b = **bptr;
std::cout << std::endl;
std::cout << "Found box w size: " << b.use << std::endl;
b.cap = 99;
std::cout << "New capacity: " << b.cap << std::endl << std::endl;
print_vec(bx);
}
出力:
Box: 1/1
Box: 2/2
Box: 3/3
Box: 4/4
Box: 5/5
Found box w size: 3
New capacity: 99
Box: 1/1
Box: 2/2
Box: 3/3
Box: 4/4
Box: 5/5
私の仮定は、3番目のボックスには、3/99を読んでいました更新した後... は、ベクターのコピーに私へのポインタのポインタを指しているということでしょう素子?