How to Insert Elements into a Vector

Inserting elements to vector in c++

During the for loop, you are modifying the vector:

After the first iteration which inserts -1, the vector becomes [1, -1, 2, 3]. Therefore, vec[1] becomes -1 rather than 2. The index of 2 becomes 2. And after inserting -2 into the vector, the index of the original value 3 becomes 4.

In the for loop condition, you need to add index i by 2, instead of 1:

#include <iostream>
#include <vector>
int main() {
std::vector < int > vek {1,2,3};
std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
for (int i = 0; i < 3 * 2; i+=2) {
std::cout << i << " " << vek[i] << std::endl;
vek.insert(vek.begin() + i + 1, -vek[i]);
}
std::cout << std::endl;
for (int i: vek) std::cout << i << " ";
return 0;
}

How to insert elements into a vector?

You can do some magic with indexes:

First create vector with output values:

probs <- rep(TRUE, 15)
ind <- c(5, 10)
val <- c( probs, rep(FALSE,length(ind)) )
# > val
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
# [13] TRUE TRUE TRUE FALSE FALSE

Now trick. Each old element gets rank, each new element gets half-rank

id  <- c( seq_along(probs), ind+0.5 )
# > id
# [1] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0
# [16] 5.5 10.5

Then use order to sort in proper order:

val[order(id)]
# [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
# [13] TRUE TRUE TRUE TRUE TRUE

Inserting a vector into a vector of vectors

Try this :

v_of_v.insert(v_of_v.begin() + index, tmp); 

how to use emplace_back to insert a new element into a vector of vector?

I can use push_back to insert a new element: data.push_back({1, 1}); In this way, I list initialized a new element, then a copy of this element is pushed to data?

exactly.

data.emplace(1, 1);

vector<Type>::emplace_back forwards its arguments to the constructor of Type. Now, std::vector<int> has a constructor that takes two integer arguments! The one specifying length (1) and fill element (1).

You can, however, inform the compiler you actually mean list initialization!

#include "fmt/format.h"
#include "fmt/ranges.h"
#include <initializer_list>
#include <vector>
int main() {
std::vector<std::vector<int>> a;
a.emplace_back(std::initializer_list<int>{1, 1});
a.emplace_back(std::initializer_list<int>{2, 2});
fmt::print("{}\n", fmt::join(a.begin(), a.end(), ";"));
}

yields the expected

 {1, 1};{2, 2}

To show it really does the in-place construction: Follow this link to gcc.godbolt.org, and observe how push_back({3,3,3,3}); actually calls the vector<int> constructor and then the insert of the vector<vector>, while emplace_back really just calls the initializer-list constructor.



Related Topics



Leave a reply



Submit