vector function to assign value to an element?
Apr 18, 2017 at 9:39pm UTC
I am looking for vector function that assigns a value to an element, and if the vector is too short, the vector is extended to the element's position.
I did not find such a function at
http://www.cplusplus.com/reference/vector/vector/ but maybe I missed something.
I could use a function something like:
1 2 3 4 5 6 7 8
vector::assignElement(unsigned int position, unsigned int val)
{
if (position >= size())
{
this .resize(position+1);
}
this .[position] = val;
}
The above function is probably has syntax errors.
Someone must have done this before, seems like there would be many uses for such a function.
How would I find such a vector function?
Thank you.
Apr 18, 2017 at 9:53pm UTC
Apr 18, 2017 at 10:03pm UTC
std::vector doesn't have such a function so you would have to write your own.
Apr 19, 2017 at 1:03am UTC
Thanks Peter87.
Here is my assignElement() function in action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include <vector>
#include <string>
#include <iostream>
struct Map
{
unsigned int mat=32;
unsigned int row=32;
unsigned int col=32;
};
struct Row
{
std::string scanner;
std::string pin;
std::vector<Map> vLayoutToKeyMatrix;
};
struct RowInv
{
std::vector<Map> vKeyMatrixToLayout;
};
struct Matrix
{
std::vector<Row> vRows;
std::vector<RowInv> vRowsInv;
};
void assignElement(std::vector<Map>& vKeyMatrixToLayout, unsigned int position, unsigned int val)
{
if (position >= vKeyMatrixToLayout.size())
{
vKeyMatrixToLayout.resize(position+1);
}
vKeyMatrixToLayout[position].col = val;
}
std::vector<Matrix> vMatrices;
void print_vRowsInv()
{
std::cout << "vRowsInv contains:" ;
for (unsigned int i=0;i<vMatrices[0].vRowsInv[0].vKeyMatrixToLayout.size();i++)
{
std::cout << " " << vMatrices[0].vRowsInv[0].vKeyMatrixToLayout[i].col;
}
std::cout << '\n' ;
}
int main()
{
vMatrices.push_back(Matrix());
//instantiate vRows
vMatrices[0].vRows.push_back(Row());
vMatrices[0].vRows[0].vLayoutToKeyMatrix.push_back(Map());
//instantiate vRowsInv
vMatrices[0].vRowsInv.push_back(RowInv());
vMatrices[0].vRowsInv[0].vKeyMatrixToLayout.resize(2);
//test assignElement()
print_vRowsInv();
assignElement(vMatrices[0].vRowsInv[0].vKeyMatrixToLayout, 4, 9);
print_vRowsInv();
}
output:
1 2
vRowsInv contains: 32 32
vRowsInv contains: 32 32 32 32 9
Topic archived. No new replies allowed.