如何在向量的开头插入元素

时间:2014-09-03 16:37:08

标签: c++ vector insert

vector<int>grid = { 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6, 4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8, 4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8 };
const size_t gridSize = end(grid) - begin(grid);
int maxColour = *max_element(begin(grid), end(grid));

vector<vector<int>> colourPos(maxColour+1);

for (size_t i = 1; i < gridSize; ++i)
    colourPos[grid[i]].push_back(i);

for (size_t i = 0; i < colourPos.size(); ++i) {
    std::cout << (i + 1) << ": ";
    for (int p : colourPos[i])
        std::cout << p << ' ';
    std::cout << std::endl;
}

如何在colourPos[1][0]处插入元素,以便它移动所有元素,还移动到colourPos向量中的其他向量?

例如[2][0][3][0]

我试过

colourPos[1][0].insert(0);

刚刚得到“表达式必须有类型”

2 个答案:

答案 0 :(得分:16)

insert使用迭代器来指示插入的位置。要在colourPos[1]的开头插入:

colourPos[1].insert(colourPos[1].begin(), 0);

答案 1 :(得分:4)

此插入有效:

vector<int> &cp1 = colourPos[1]; // & means reference to the subarray
cp1.insert(cp1.begin(), 2);      // insertion