Add a Series of Elements in Different Locations Within a Vector

Inserting multiple elements at same position in a vector

You can use nested vector to insert more than one values at a position.

Declaration vector< vector<int> > adj[V];

Now to insert a value at position 0 you can use like this

void addEdge(vector<int> adj[], int u, int v, int val) 
{
adj[u][v].push_back(val);
adj[v][u].push_back(val);
}

To add element

addEdge(adj, 0, 0, 1); // insert 1 at position (0,0)

Please keep in mind that before adding element you need to initialize vector at every index.

But you can't insert two or more values at same position in vector.

How do I pass multiple ints into a vector at once?

Try pass array to vector:

int arr[] = {2,5,8,11,14};
std::vector<int> TestVector(arr, arr+5);

You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.

If you use C++11, you can try:

std::vector<int> v{2,5,8,11,14};

Or

 std::vector<int> v = {2,5,8,11,14};

How to sum up elements of a C++ vector?

Actually there are quite a few methods.

int sum_of_elems = 0;

C++03

  1. Classic for loop:

     for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
    sum_of_elems += *it;
  2. Using a standard algorithm:

     #include <numeric>

    sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);

    Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.

C++11 and higher


  1. b. Automatically keeping track of the vector type even in case of future changes:

     #include <numeric>

    sum_of_elems = std::accumulate(vector.begin(), vector.end(),
    decltype(vector)::value_type(0));
  2. Using std::for_each:

     std::for_each(vector.begin(), vector.end(), [&] (int n) {
    sum_of_elems += n;
    });
  3. Using a range-based for loop (thanks to Roger Pate):

     for (auto& n : vector)
    sum_of_elems += n;

C++17 and above


  1. Using std::reduce which also takes care of the result type, e.g if you have std::vector<int>, you get int as result. If you have std::vector<float>, you get float. Or if you have std::vector<std::string>, you get std::string (all strings concatenated). Interesting, isn't it?

    auto result = std::reduce(v.begin(), v.end());

    There are other overloads of this function which you can run even parallelly, in case if you have a large collection and you want to get the result quickly.

How can I insert multiple numbers to a particular element of a vector?

If you know how many indices you want ahead of time, then try std::vector<std::vector<int>> (or instead of int use double or whatever).

For instance, if you want a collection of numbers corresponding to each number from 0 to 9, try

//This creates the vector of vectors, 
//of length 10 (i.e. indices [0,9])
//with an empty vector for each element.
std::vector<std::vector<int>> vec(10, std::vector<int>());

To insert an element at a given index (assuming that there is something there, so in the above case there is only 'something there' for elements 0 through 9), try

vec.at(1).push_back(5);
vec.at(1).push_back(3);

And then to take the sum of the numbers in the vector at index 1:

int sum = 0;
for (int elem : vec.at(1)) { sum += elem; }
//sum should now be 8

If you want it to work for arbitrary indices, then it should be

std::map<int, std::vector<int>> map;
map[1].push_back(5); //creates an empty vector at index 1, then inserts
map[1].push_back(3); //uses the existing vector at index 1
int sum = 0;
for (int elem : map.at(1)) { sum += elem; }

Note that for std::vector and std::map, using [] do very different things. Most of the time you want at, which is about the same for both, but in this very specific case, [] for std::map is a good choice.

EDIT: To sum over every element in every vector in the map, you need an outer loop to go through the vectors in the map (paired with their index) and an inner loop like the one above. For example:

int sum = 0;
for (const std::pair<int, std::vector<int>>& index_vec : map) {
for (int elem : index_vec.second) { sum += elem; }
}

Usage of for range in Vectors in order to add elements

The reason that (amongst other things) a range-based for loop shouldn't append elements is because behind the curtains, a range-based for loop is just a loop that iterates over the container's iterators from begin to end. And std::vector::push_back will invalidate all iterators:

If the new size() is greater than capacity() then all iterators and
references (including the past-the-end iterator) are invalidated.
Otherwise only the past-the-end iterator is invalidated.

Contrary to using iterators, however, the same cannot be said when indexing the vector, because even if push_back invalidats iterators, vec[3] will always refer to the element at position 3 (assuming size() > 3).

Furthermore, the loop you show does not even iterate over the vector's elements. It just adds more elements to an existing vector, and it is not a range-based for loop.

To be clear, a construct that would be a problem would be the following:

std::vector<int> vec(10); // 10 times a zero
vec[0] = 1;
for (int k: vec)
if (k == 1)
vec.push_back(2); // invalidates iterators!

While this, equivalent looking code, is legal:

std::vector<int> vec(10); // 10 times a zero
vec[0] = 1;
for (std::size_t i = 0; i < std::size(vec); ++i)
if (vec[i] == 1)
vec.push_back(2);

How to insert an element at a specific position of an empty vector?

You need to do this in two steps:

  1. First resize the vector or create a vector with an appropriate size.
  2. Next set the elements accordingly.

Since you are coming from R I assume you want the vector to be initially filled with missing values. Here is the way to do this.

In my example I assume you want to store integers in the vector. Before both options load the Missings.jl package:

using Missings

Option 1. Start with an empty vector

julia> x = missings(Int, 0)
Union{Missing, Int64}[]

julia> resize!(x, 4)
4-element Vector{Union{Missing, Int64}}:
missing
missing
missing
missing

julia> x[1] = 10
10

julia> x[4] = 40
40

julia> x
4-element Vector{Union{Missing, Int64}}:
10
missing
missing
40

Option 2. Preallocate a vector

julia> x = missings(Int, 4)
4-element Vector{Union{Missing, Int64}}:
missing
missing
missing
missing

julia> x[1] = 10
10

julia> x[4] = 40
40

The reason why Julia does not resize the vectors automatically is for safety. Sometimes it would be useful, but most of the time if x is an empty vector and you write x[4] = 40 it is a bug in the code and Julia catches such cases.



EDIT

What you can do is:

function setvalue(vec::Vector, idx, val)
@assert idx > 0
if idx > length(vec)
resize!(vec, idx)
end
vec[idx] = val
return vec
end

Insert elements into a vector at given indexes

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


Related Topics



Leave a reply



Submit