How to keep iterating over data structure after inserting elements into it? - c++

In the code snippet below, I insert Instruction's into the BasicBlock pointed to by Function::iterator bs. The inner loop iterates over the instructions contained within this BasicBlock.
Now, after the inner loop inserts these instructions, the program goes into an infinite loop with instruction sequence:
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
...
How would I insert into the data structure being iterated over, while avoiding going into an infinite loop?
Somehow the iterator goes nuts (or it is invalidated). Is there a common idiom for how to tackle this problem?
for (Function::iterator bs = F.begin(), be = F.end(); bs != be; ++bs) {
for (BasicBlock::iterator is = bs->begin(), ie = be->end(); is != ie; ++is) {
Instruction& inst = *is;
BinaryOperator* binop = dyn_cast<BinaryOperator>(&inst);
if (!binop) {
continue;
}
unsigned opcode = binop->getOpcode();
errs() << binop->getOpcodeName() << "\n";
if (opcode != Instruction::Add) {
continue;
}
IRBuilder<> builder(binop);
Value* v = builder.CreateAdd(builder.CreateXor(binop->getOperand(0), binop->getOperand(1)),
builder.CreateMul(ConstantInt::get(binop->getType(), 2),
builder.CreateAnd(binop->getOperand(0), binop->getOperand(1))));
ReplaceInstWithValue(bs->getInstList(), is, v); // THINGS GO WRONG HERE!
}
}

Unfortunately, you failed to provide sufficient details, but I strongly suspect that you're inserting a new element into a container in such a way that existing iterators (to other elements) are invalidated. This is the usual behaviour for many container classes, e.g. std::vector<>::insert(), which invalidates all existing iterators if the new size() exceeds capacity() (otherwise only existing iterators to elements before the insertion point remain valid).
The way to avoid this is to use a container that does not suffer from this problem, e.g. a std::list<>, since std::list<>::insert() does not invalidate any existing iterator or reference.

Related

Removing first three elements of 2d array C++

So here's my problem.. I have a 2d array of 2 char strings.
9D 5C 6S 9D KS 4S 9D
9S
If 3 found I need to delete the first 3 based on the first char.
card
My problem is I segfault almost anything i do...
pool is the 2d vector
selection = "9S";
while(col != GameBoard::pool.size() ){
while(GameBoard::pool[col][0].at(0) == selection.at(0) || cardsRem!=0){
if(GameBoard::pool[col].size() == 1){
GameBoard::pool.erase(GameBoard::pool.begin() + col);
cardsRem--;
}
else{
GameBoard::pool[col].pop_back();
cardsRem--;
}
}
if(GameBoard::pool[col][0].at(0) != selection.at(0)){
col++;
}
}
I've tried a series of for loops etc, and no luck! Any thoughts would save my sanity!
So I've tried to pull out a code segment to replicate it. But I can't...
If I run my whole program in a loop it will eventually throw a segfault. If I run that exact code in the same circumstance it doesn't... I'm trying to figure out what I'm missing. I'll get back in if I figure out exactly where my issue is..
So in the end the issue is not my code itself, i've got memory leaks or something somewhere that are adding up to eventually crash my program... That tends to be in the same method each time I guess.
The safer and most efficient way to erase some elements from a container is to apply the erase-remove idiom.
For instance, your snippet can be rewritten as the following (which is testable here):
using card_t = std::string;
std::vector<std::vector<card_t>> decks = {
{"9D", "5C", "6S", "9D", "KS", "4S", "9D"},
{"9S"}
};
card_t selection{"9S"};
// Predicate specifing which cards should be removed
auto has_same_rank = [rank = selection.at(0)] (card_t const& card) {
return card.at(0) == rank;
};
auto & deck = decks.at(0);
// 'std::remove_if' removes all the elements satisfying the predicate from the range
// by moving the elements that are not to be removed at the beginning of the range
// and returns a past-the-end iterator for the new end of the range.
// 'std::vector::erase' removes from the vector the elements from the iterator
// returned by 'std::remove_if' up to the end iterator. Note that it invalidates
// iterators and references at or after the point of the erase, including the
// end() iterator (it's the most common cause of errors in code like OP's).
deck.erase(std::remove_if(deck.begin(), deck.end(), has_same_rank),
deck.end());
So for anyone else in the future who comes across this...
The problem is I was deleting an element in the array in a loop, with the conditional stop was it's size. The size is set before hand, and while it was accounted for in the code it still left open the possibility for while(array.size() ) which would be locked in at 8 in the loop be treated as 6 in the code.
The solution was to save the location in the vector to delete and then delete them outside of the loop. I imagine there is a better, more technical answer to this, but it works as intended now!
for (double col = 0; col < size; ++col)
{
if(GameBoard::pool[col][0].at(0) == selection.at(0)){
while(GameBoard::pool[col][0].at(0) == selection.at(0) && cardsRem !=0){
if( GameBoard::pool[col].size() > 1 ){
GameBoard::pool[col].pop_back();
cardsRem--;
}
if(GameBoard::pool[col].size() <2){
toDel.insert ( toDel.begin() , col );
//GameBoard::pool.erase(GameBoard::pool.begin() + col);
cardsRem--;
size--;
}
}
}
}
for(int i = 0; i< toDel.size(); i++){
GameBoard::pool.erase(GameBoard::pool.begin() + toDel[i]);
}

How to get int position of vector loop

How to get int position of this loop? Thank you.
auto a = vect.begin();
auto b = vect2.begin();
auto c = vect3.begin();
for (; a != vect.end() && b != vect2.end() && c != vect3.end(); a++, b++, c++) {
}
I need to print values of other variable, but I need to get actual unsigned int position of this vector loop.
I need to print double vector using this position of this vector.
And how to get the last index of vector.
My problem is for for loop with multiple vectors and getting index from it next to use only last of indexes.
As Angew shows, a simple indexed loop may be preferable when you need indices.
However, it is possible to get the index from an iterator as well:
auto a = vect.begin();
auto b = vect2.begin();
auto c = vect3.begin();
for (/*the loop conditions*/) {
auto index = a - vect.begin();
}
It is also possible to get the index of a forward iterator using std::distance, but it would be unwise to use it in a loop, since the complexity will be linear for non-random-access iterators.
In the case of forward iterators (and generic code that must support forward iterators), you can write a loop which has both the index variable, and the iterators.
P.S. it is potentially preferable to use pre-increment with iterators. Probably only matters in debug build.
It's simple: if you need indices, don't use iterators:
for (
size_t idx = 0, idxEnd = std::min({vect.size(), vect2.size(), vect3.size()});
idx < idxEnd;
++idx
)
{
auto& obj1 = vect[idx];
auto& obj2 = vect2[idx];
auto& obj3 = vect3[idx];
}
(The above code initialises idxEnd once at the start of the loop, so that it's not needlessly recomputed at each iteration. It's just an optimisation).

Fast algorithm to remove odd elements from vector

Given a vector of integers, I want to wrote a fast (not obvious O(n^2)) algorithm to remove all odd elements from it.
My idea is: iterate through vector till first odd element, then copy everything before it to the end of vector (call push_back method) and so on until we have looked through all original elements (except copied ones), then remove all of them, so that only the vector's tail survive.
I wrote the following code to implement it:
void RemoveOdd(std::vector<int> *data) {
size_t i = 0, j, start, end;
uint l = (*data).size();
start = 0;
for (i = 0; i < l; ++i)
{
if ((*data)[i] % 2 != 0)
{
end = i;
for (j = start, j < end, ++j)
{
(*data).push_back((*data)[j]);
}
start = i + 1;
}
}
(*data).erase((*data).begin(), i);
}
but it gives me lots of errors, which I can't fix. I'm very new to the programming, so expect that all of them are elementary and stupid.
Please help me with error corrections or another algorithm implementation. Any suggestions and explanations will be very appreciative. It is also better not to use algorithm library.
You can use the remove-erase idiom.
data.erase(std::remove_if(data.begin(), data.end(),
[](int item) { return item % 2 != 0; }), data.end());
You don't really need to push_back anything (or erase elements at the front, which requires repositioning all that follows) to remove elements according to a predicate... Try to understand the "classic" inplace removal algorithm (which ultimately is how std::remove_if is generally implemented):
void RemoveOdd(std::vector<int> & data) {
int rp = 0, wp = 0, sz = data.size();
for(; rp<sz; ++rp) {
if(data[rp] % 2 == 0) {
// if the element is a keeper, write it in the "write pointer" position
data[wp] = data[rp];
// increment so that next good element won't overwrite this
wp++;
}
}
// shrink to include only the good elements
data.resize(wp);
}
rp is the "read" pointer - it's the index to the current element; wp is the "write" pointer - it always points to the location where we'll write the next "good" element, which is also the "current length" of the "new" vector. Every time we have a good element we copy it in the write position and increment the write pointer. Given that wp <= rp always (as rp is incremented once at each iteration, and wp at most once per iteration), you are always overwriting either an element with itself (so no harm is done), or an element that has already been examined and either has been moved to its correct final position, or had to be discarded anyway.
This version is done with specific types (vector<int>), a specific predicate, with indexes and with "regular" (non-move) assignment, but can be easily generalized to any container with forward iterators (as its done in std::remove_if) and erase.
Even if the generic standard library algorithm works well in most cases, this is still an important algorithm to keep in mind, there are often cases where the generic library version isn't sufficient and knowing the underlying idea is useful to implement your own version.
Given pure algorithm implementation, you don't need to push back elements. In worst case scenario, you will do more than n^2 copy. (All odd data)
Keep two pointers: one for iterating (i), and one for placing. Iterate on all vector (i++), and if *data[I] is even, write it to *data[placed] and increment placed. At the end, reduce length to placed, all elements after are unecessary
remove_if does this for you ;)
void DeleteOdd(std::vector<int> & m_vec) {
int i= 0;
for(i= 0; i< m_vec.size(); ++i) {
if(m_vec[i] & 0x01)
{
m_vec.erase(m_vec.begin()+i);
i--;
}
}
m_vec.resize(i);
}

Sorting list using iterators won't sort last element C++

so I'm trying to sort a list of lists. Inside of each sublist the elements are classes that contains a runtime. This is the integer variable I am using to sort my list.
However, the list will not 100% sort itself if the smallest runtime is at the end of the list. I have a attached an image below of the terminal output for visualization.
Here is the code:
void sort( list<list<MetaData> > &omegaList )
{
// variables
list<list<MetaData> >::iterator cursor = omegaList.begin();
list<list<MetaData> >::iterator ptr = omegaList.begin();
list<list<MetaData> >::iterator end = omegaList.end();
// start the bubble sort...
for(; cursor != end; cursor++)
{
// iterate through the list
for(; ptr != end; ptr++)
{
// compare runtimes of different lists
if( ptr->front().getProcessRunTime() < cursor->front().getProcessRunTime() )
{
// swap locations of lists in omegaList
swap( *ptr, *cursor );
// reset
cursor = ptr = omegaList.begin();
}
}
}
}
And the output:
If anybody could please explain to me WHY it won't look at the very last element and then tell me how to fix it I would appreciate it.
The proper way to do the sort is with std::list::sort as follows:
omegaList.sort(
[](const list<MetaData>& lhs, const list<MetaData>& rhs) {
return lhs.front().getProcessRunTime() <
rhs.front().getProcessRunTime();
});
You can see that run here.
In your bubble sort, the reason your first element is not getting sorted is that as soon as you find an out-of-order element, you do this...
cursor = ptr = omegaList.begin();
...then the ptr++ for-loop operation kicks in and your sorting therefore restarts at begin() + 1. That cursor = ptr = omegaList.begin(); is pretty wild - first O(n^3) sort implementation I've ever seen.

Replace an element with old_value to new_value in vector - C++

I was going through some legacy code, and found out something that could be improved.
The vector has pointers to a class and all elements are unique in the vector, as per the design.
A function ReplaceVal replaces an element having old_value to a new_value in the vector, in the following fashion:
iterator i, i_e;
i = vector->begin();
i_e = vector->end ();
for (; i != i_e; ++i)
{
if ((*i) == old_child)
break;
}
// Insertion
vector->insert_call(new_child, i);
// Since, the pointers are invalidated, do another find for erase
i = vector->begin();
i_e = vector->end ();
for (; i != i_e; ++i)
{
if ((*i) == old_child)
break;
}
// Finally, erase the old_value
vector->erase_call(i);
So, essentially, this involves shifting of elements twice, each for insertion and erase, if you are inserting and erasing elements in the middle of the vector.
For n insertions and remove calls, the complexity is O(n*m), if m elements are shifted every time, on an average.
I think, this can be improved, if I use std::replace, as mentioned here # MSDN documentation and std_replace_example.
The complexity of the std::replace would be O(n) comparisons for the old_value and new_value & 1 assignment operation. It'd be as simple as:
replace (vector.begin( ), vector.end( ), old_value , new_value);
Please correct me, if I am wrong and share feedback on anything that I missed.
P.S. The insert and erase are custom calls, which also update pointers to left_sibling and right_sibling for a given element.
You don't even need to do that:
iterator position = std::find( vector->begin() vector->end(), old_child );
if ( position == vector->end() ) {
throw NoSuchElement();
}
*position = new_child;
should do the trickā€”no erase and no insert.
vector erase returns an iterator pointing to location of the element that followed the erased
iter = myvector->erase(i);
then you can use that iterator to insert.
myvector->inster(iter, new_value);
or the other way around. vector insert returns an iterator pointing to the inserted element
iter = myvector->inster(i, new_value);
myvector->erase(iter);
Why not use one of these?
std::set
std::multiset
std::unordered_set
std::unordered_multiset
Why you have such complexity? Is there any purpose. May be the vector is used somewhere else also, but you may also use sets along with vectors for searching.