0

I have the Bitcoin source code (multithreaded) and I'm intending to add some new lines. On Bitcoin network data messages are exchanged where data are stored in vectors. I want to implement some instrunction whenever a vector increases in size:

How can I code following pattern in C++ in order to execute statements inside if:

if ("vVector.size() did not increase")
//*instruction*

?

NOTE: vVector is incremented automatically from time to time. It's actually a clone of another vector that collects things and expands without me having and willing to have control on it.

EDIT:

When I do:

if (!(vVector.size()++))
//do whatever is here

I get following error: lvalue required as increment operand

vVector is filled inside another function of the same cpp-file by a function that is declared in a separate header file.

here's a code snippet with a short description: http://hastebin.com/amisuvafab.coffee

Aliakbar Ahmadi
  • 366
  • 3
  • 14

2 Answers2

4
int init_size = v.size();
...
if(init_size == v.size()) {
  // do whatever is here
}

On Edit:

A std::vector's size is increased only if you insert an element to it. Thus, vVector.size()++ makes no sense in the first place.

The reason you're getting the error is because, doing if(!(vVector.size()++)) is illegal. std::vector::size member function will return an rvalue instead of an lvalue that the post-increment operator++ requires. Now on the difference between an rvalue and lvalue see this link.

Community
  • 1
  • 1
101010
  • 41,839
  • 11
  • 94
  • 168
3

As simple as this

int prevSize = vVector.size();
// do something here

if (vVector.size() == prevSize) {
    // do whatever is here.
}

EDIT

if (!(vVector.size()++))

This statement is plain wrong. size() method returns the value (const) of the size of vector, not the reference. So you cannot increment it. AddInventoryHonest() adds to the vector using push_back(). So the return value of size() method will change with every call to push_back. Hence this will work in this scenario.

EDIT 2: To handle the multithreaded case, use condition variable (just an example)

int prevSize = vVector.size();
// do something

std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
std::condition_variable cv;

bool size_did_not_increase() {
    return vVector.size() == prevSize;
}

cv.wait(lck, size_did_not_increase());
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50