AlmuHS - 1 year ago 94
C++ Question

# How can I insert a element in a STL vector matrix?

I'm writing a code for create a adjacency_matrix using STL vector class

My matrix is this:

``````vector<vector<float> > adjacency_matrix;
``````

I need to know how can I insert new values in the matrix, similar to v[x][y] = z

I try this code, but it fails:

``````    adjacency_matrix.insert((adjacency_matrix.begin()+node1).begin()+node2,distance);
``````

Example

I have this

```0 [] 7 9 2.6 0 [] 3.5 [] [] 0 [] [] [] [] 0```

Then, I have to insert 12.5 value in (3,2) position
The result must be this:

```0 [] 7 9 2.6 0 [] 3.5 [] [] 0 [] [] 12.5 [] 0```

Can you help me?

`std::vector` is continuous, resizable array of values. You can't access its x element if it wasn't previously initialized altogether with elements before it. This would be undefined behaviour.

So you should create the whole matrix beforehand like that:

``````auto m_size = 10;
std::vector<std::vector<float>> matrix(m_size, std::vector<float>(m_size, 0.0));
matrix[1][3] = 1.0;
std::cout << matrix[0][0]; // 0.0
std::cout << matrix[1][3]; // 1.0

// still BAD, because we initialized only matrix of size 10; we could, however, expand it e.g. with vector::push_back
matrix[13][0] = 2; // UB: crash
``````

If you can't do that, you could use `std::map`, which creates default elements automatically when `operator[]` is called (note however that map is actually a tree, and `operator[]` performs a logarithmic search instead of vector's constant access):

``````std::map<size_t, std::map<size_t, float>> matrix;
matrix[0][1] = 3.0;
std::cout << matrix[0][0];  // 0.0
std::cout << matrix[0][1];  // 3.0
``````

If uninitialized values are indeterminate, you can express that with e.g. `std::optional`:

``````std::map<size_t, std::map<size_t, std::optional<float>>> matrix;
matrix[0][1] = 5.0;
std::cout << matrix[0][0].value_or(127.0); // 127.0
std::cout << *(matrix[0][1]); // 5.0

if (matrix[14][27])
std::cout << *(matrix[14][27]);
else
std::cout << "not initialized";
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download