How can I improve this code?

I wrote this code but how can I improve it without using at least two while

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  auto _Length = DataBlockCount * DataBlockLength;
  vector<double> totalPacket;
  vector<double> middlePacket;

  if (AllData.size() >= int(_Length)) {
    totalPacket = AllData;
  } else if (AllData.size() < int(_Length)) {

    while (totalPacket.size() < int(_Length)) {
      // append next packet that received
      middlePacket = totalPacket.insert(
          middlePacket.end(), DataBlockLength.begin(), DataBlockLength.end());
    }
  }
  while (int(DataBlockLength) < totalPacket.size()) {
    //
    // some code for get the middle of packet
    //

    for (int i = 0; i < int(DataBlockLength / 2); i++) {
      samples[i] = middlePacket[i];
    }

    totalPacket.erase(0, DataBlockLength);
Last edited on
You could start by using consistent indentation.
@helios In style? Sorry, I fix it
What is the code supposed to do? Without a way to do a test by including a full working snippet it is hard to suggest anything.

Does the code do what you want without being a major waste of resources? Then does it really need to be "improved?"
all we can do is guess, but if you can get at the part you want in the second while loop in the first one, then just use 1 loop even if it does 2 things, speed > split if you need speed.
if you depend on the first loop to complete to get the second, it is what it is.
1
2
3
4
5
DataBlockCount * DataBlockLength

DataBlockLength.begin(), DataBlockLength.end()

int(DataBlockLength)

What is the type of this DataBlockLength?
Has members begin() and end(), converts to int, and is accepted by some op* ...


1
2
3
vector<double> totalPacket;
vector<double> middlePacket;
middlePacket = totalPacket.insert( middlePacket.end(), ...

while:
iterator vector::insert( const_iterator position, InputIterator first, InputIterator last ); position
Position in the vector where the new elements are inserted.

This needs explanation.
> auto _Length = DataBlockCount * DataBlockLength;

Avoid using identifiers that start with an underscore followed by an upper case character.

. the identifiers with a double underscore anywhere are reserved;
. the identifiers that begin with an underscore followed by an uppercase letter are reserved;
. the identifiers that begin with an underscore are reserved in the global namespace.

"Reserved" here means that the standard library headers #define or declare such identifiers for their internal needs, the compiler may predefine non-standard identifiers of that kind, and that name mangling algorithm may assume that some of these identifiers are not in use. If the programmer uses such identifiers, the behavior is undefined.
https://en.cppreference.com/w/cpp/language/identifiers#In_declarations
Registered users can post here. Sign in or register to post.