Today, I'm working on understanding some new-to-me features, particularly std::array
and std::vector
. Individually, these seem to behave as expected, but I'm very puzzled by the behavior illustrated below:
This version works:
printf("Using pointer:\n");
std::vector<std::array<int, 1>*> vap;
vap.push_back(new std::array<int, 1>());
printf("size of vector is %ld\n", vap.size());
printf("before setting value:\n");
printf("value is %d\n", vap.front()->at(0));
std::array<int, 1>* pvals = vap.front();
pvals->at(0) = -1;
printf("after setting value:\n");
printf("value is %d\n", vap.front()->at(0));
This version doesn't update the array:
printf("Without pointer:\n");
std::vector<std::array<int, 1>> va;
std::array<int, 1> arr = {99};
va.push_back(arr);
Inserting the array like this fails too: va.push_back(std::array<int, 1>());
printf("size of vector is %ld\n", va.size());
printf("before setting value:\n");
printf("value is %d\n", va.front().at(0));
std::array<int, 1> vals = va.front();
vals[0] = -1;
printf("after setting value:\n");
printf("value is %d\n", va.front().at(0));
It's likely obvious what I'm trying to do but, in case it helps, I'll write it in prose:
Loosely, I'm creating a vector of arrays of ints. In the first half of the example, I create a vector of pointers to those arrays, and am able to insert a new array, via a pointer, and then modify the element contained in that array. In the second half, I tried to avoid using pointers. That code seems to insert the array successfully but then does not allow me to alter the element within it.
I'm somewhat surprised that there are zero warnings or errors, either at compile or runtime, and I'm guessing that I'm missing something fundamental. What can I try next?
You are working on a copy of the array, you need a reference to the array in the vector
int main() {
vector<array<int, 1>> v;
array<int, 1> a = { 99 };
v.push_back(a);
cout << v[0][0];
auto& ar = v[0];
ar[0] = 42;
cout << v[0][0];
}
gives
99 42