Inserting into a vector at the front
The efficiency of obtaining the insertion point won't matter in the least - it will be dwarfed by the inefficiency of constantly shuffling the existing data up every time you do an insertion.
Use std::deque for this, that's what it was designed for.
Why doesn't std::vector::push_front() exist?
You don't want to push_front on a vector ever. Adding an element to the front means moving every single other element in the vector one element back: O(n) copying. Terrible performance.
Inserting a vector in a certain position in another vector
I want to insert vector
b
in a certain position in a vectora
You may want to consider std::vector::insert()
:
vecta.insert(pos, vectb.begin(), vectb.end());
where pos
above is an iterator pointing to the element (in vecta
) before the content of vectb
will be inserted. pos
may be also the iterator returned by end()
, which would mean appending the content of vectb
to vecta
.
How can I have a result vector to be like {10,20,1000,2000,3000,40,50}
For that, you also need to remove the element 30
from vecta
. You can do this with std::vector::erase()
:
auto main() -> int {
std::vector <int> vecta{ 10, 20, 30, 40 , 50};
/* ^
|-- insert vectb here and replace the 30
*/
std::vector <int> vectb{ 1000, 2000, 3000 };
// what element to erase from vecta?
auto pos = vecta.begin() + 2;
// erase it
pos = vecta.erase(pos);
// insert vectb in vecta
vecta.insert(pos, vectb.begin(), vectb.end());
for (auto& e: vecta)
std::cout << e << " ";
std::cout << std::endl;
}
std::vector::erase()
returns the iterator that follows the removed element. Since you want to erase 30
from vecta
and then insert vectb
at that position, you can simply pass the iterator erase()
returns to insert()
.
How to insert element at beginning of vector
insert
takes an iterator to indicate where to insert. To insert at the beginning of colourPos[1]
:
colourPos[1].insert(colourPos[1].begin(), 0);
Inserting and deleting elements from vector *at the same time*
Modifying it in place is a no-go.
Consider that you have to insert something at every position. You would need to copy every single item into a temp place then copy them back.
You might argue that you could do it from the end, backwards. But if we have some deletions we would also need to store some of the elements there, potentially getting back to copying every element into some temp storage and back.
I think the fastest way would be to allocate a new array, and build it up, using the original as temp storage. This way you are guaranteed that each element is copied exactly once.
Now, depending on the types used (like ints, or pointers) this could be a lot faster than anything else you might cook up. If copies are expensive consider using moves, or pointers.
If you are worried about performance, you should benchmark you code and tune it. It's hard to argue precisely about performance without data.
Add an element into the beginning of an vector, rest elements' position will add one
http://www.cplusplus.com/reference/vector/vector/insert/
The following would be an example
int main ()
{
std::vector<int> myvector;
int myarray [] = { 1,2,3,4,5 };
myvector.insert (myvector.begin(), myarray, myarray+5);
// Insert another value
myvector.insert (myvector.begin(), 6);
return 0;
}
Inserting multiple values into a vector at specific positions
One way is to create another vector with capacity equal to the original size plus the number of the elements being inserted and then do an insert loop with no reallocations, O(N) complexity:
template<class T>
std::vector<T> insert_elements(std::vector<T> const& v, std::initializer_list<std::pair<std::size_t, T>> new_elements) {
std::vector<T> u;
u.reserve(v.size() + new_elements.size());
auto src = v.begin();
size_t copied = 0;
for(auto const& element : new_elements) {
auto to_copy = element.first - copied;
auto src_end = src + to_copy;
u.insert(u.end(), src, src_end);
src = src_end;
copied += to_copy;
u.push_back(element.second);
}
u.insert(u.end(), src, v.end());
return u;
}
int main() {
std::vector<int> v{1, 3, 5};
for(auto e : insert_elements(v, {{1,2}, {2,4}}))
std::cout << e << ' ';
std::cout << '\n';
}
Output:
1 2 3 4 5
Inserting an element at the beginning of Vector
Can you use a java.util.LinkedList
instead? You can then use addFirst
, which should be more efficient since it is a doubly-linked list.
Related Topics
Why Does My Program Hang When Opening a Mkfifo-Ed Pipe
Passing Variable Number of Arguments with Different Type - C++
When Do We Need to Pass the Size of Array as a Parameter
Cpu Dispatcher for Visual Studio for Avx and Sse
Somehow Register My Classes in a List
Arithmetic Right Shift Gives Bogus Result
If I Want to Specialise Just One Method in a Template, How to Do It
Program Is Generating Same Random Numbers on Each Run
C++ Fatal Error Lnk1120: 1 Unresolved Externals
Is It Ok to Use C-Style Cast for Built-In Types
Configuring Compilers on MAC M1 (Big Sur, Monterey) for Rcpp and Other Tools
How to Create a Temporary Directory in C++
Cmake Cannot Determine Linker Language for Target
Math Precision Requirements of C and C++ Standard
How to Connect a Signal to a Static Slot Without a Receiver Instance