简体   繁体   English

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

[英]How to insert element at beginning of vector

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;
}

How can I insert an element at colourPos[1][0] so that it shifts all elements, and also to the other vectors within the colourPos vector? 如何在colourPos[1][0]插入一个元素,以便它移动所有元素,还移动到colourPos向量中的其他向量?

eg [2][0] , [3][0] . 例如[2][0][3][0]

I tried 我试过了

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

and just got "expression must have class type" 并得到“表达必须有类型”

insert takes an iterator to indicate where to insert. insert接受一个迭代器来指示插入的位置。 To insert at the beginning of colourPos[1] : 要在colourPos[1]的开头插入:

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

This insertion works: 此插入有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将元素插入到向量的开头? - How can I insert element into beginning of vector? 使用std :: move在开始时插入向量的中间元素不起作用 - Using std::move to insert middle element of a vector at the beginning not working 使用递归时如何在开头插入元素? - how to insert an element in the beginning when using recursion? 如果我知道元素的数量,如何在 std::vector 的开头插入一个新元素而没有任何复制和默认构造开销? - How to insert a new element at the beginning of std::vector without any copy and default constructing overhead if I know the number of elements? 如何创建重载运算符以将新元素添加到向量的开头或结尾 с++ - how to create an overload operator for adding a new element to the beginning or end of a vector с++ 移动向量的最后一个元素 <vector<int> &gt;开始 - Move last element of vector<vector<int>> to beginning 如何使用 emplace_back 将新元素插入向量的向量中? - how to use emplace_back to insert a new element into a vector of vector? 将元素插入结构向量 - Insert element into struct vector 如何在字符串流的开头插入字符串 - How to insert a string to the beginning of a stringstream 如何将元素插入向量而不是向量中已存在的元素? - How can I insert element to vector instead the element already exists in the vector?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM