Replace an element into a specific position of a vector
Asked Answered
W

4

66

I want to replace an element into a specific position of a vector, can I just use an assignment:

// vec1 and 2 have the same length & filled in somehow
vec1;
vec2;

vec1[i] = vec2[i] // insert vec2[i] at position i of vec1

or I have to use insert():

vector<sometype>::iterator iterator = vec1.begin();

vec1.insert(iterator+(i+1), vec2[i]);
Williwaw answered 17/7, 2011 at 21:14 Comment(2)
Be careful of your phrasing here. Insert will mean adding an element at a location and moving all subsequent elements up one place in the vector (ie growing the vector by one element). On the other hand you can use setting to indicate you want to change an existing vector element to a new value.Lyndes
i think what i want is to replace whatever at vec1[i] with vec2[i]; and in my case vec[i] can be null, and i want to keep the lengths of vec1 and 2 the same;Williwaw
I
109
vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])
Irishman answered 17/7, 2011 at 21:16 Comment(0)
D
14

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0
Dygall answered 2/11, 2015 at 11:28 Comment(0)
I
2

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Indeterminable answered 17/7, 2011 at 21:24 Comment(0)
K
0

Don't use std::vector::insert if you want to use reserved memory and don't want to change the size of your buffer, try to use memcpy instead as below:

auto begin = static_cast<const uint8_t*>(data);
memcpy(&data_buffer[write_pos], begin, size);
Killerdiller answered 22/12, 2021 at 5:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.