I have some code like this:

vector<double> Saved;
for(int i = 0; i<10; i++)
{
  if(some condition on i)
      Saved.push_back(i);
}

Then I want to see what order the things were saved... so naturally I do

cout << (0) << endl << (1) << endl;

But to my surprise they aren't in the right order!! Pretty odd if you ask me...

I would expect the first thing output there to always be less than the second thing... correct??

The actual code follows, but relies on a bunch of stuff so I don't think it will be very helpful:

for(int scancounter = 0; scancounter < NumScans; scancounter++) //alpha loop

	{

		for(int concentriccol = 0; concentriccol < ColsPerScan; concentriccol++) //beta loop

		{
			B.clear();
			V1.clear();
			V2.clear();

			B = LiDARGrid.ConcentricScans.at(scancounter).getColumn(concentriccol);	

		
			double Penalty = CreateComparableVectors(A,B,V1,V2);


			double distance = VectorDistance(V1,V2) + Penalty;


			if(distance < 100) //distance bigger than this is unreliable

			{
				if(distance <= BestDistance)

				{

					BestDistance = distance;

					BestScanPositions.push_back(scancounter);

					BestCols.push_back(concentriccol);

				}
			}
			

		}//end col loop

	}//end scanner loop

	cout << "Input Scan: " << CorrectPosition << " Col: " << CorrectCol << endl

			<< "Matching Scans: " << endl
			<< BestScanPositions.at(0) << " Col: " << BestCols.at(0) << endl
			<< BestScanPositions.at(1) << " Col: " << BestCols.at(1) << endl
			<< "Best Distance: " << BestDistance << endl
			<< "There were " << BestScanPositions.size() << " good matches." << endl << endl;

An example is (0) is 0 and (1) is also 0. Then (0) is 19 and (1) is 16!!! Weird, eh?

Please let me know if I'm doing something wrong..

Thanks,

Dave

Dani AI

Generated

Std::vector::push_back appends elements in the exact order it’s called; the container itself does not reorder or “shuffle” values. Given the thread, that means the surprising ordering is almost certainly coming from the calling logic (when and how push_back is invoked), not from push_back itself. ’s reminder about normal access, ’s bounds-checking warning, and ’s hint about forgetting to clear state are all relevant starting points.

Quick, practical checks (trace-first diagnostics)

  • Add a small log immediately before every push to confirm the pair (scan, col, distance) that’s being stored and the exact sequence of pushes. That will reveal whether the algorithm is discovering matches in the unexpected order or whether stored values are being corrupted later.
  • Ensure the “best” threshold/initial value is set correctly (use a large initial value via std::numeric_limits<double>::infinity()) and that the intent of the condition (store every match vs. store only the best) is implemented consistently.

Example tracing pattern (illustrative)

struct Match { int scan; int col; double dist; };
std::vector<Match> matches;

for (int s = 0; s < NumScans; ++s) {
    for (int c = 0; c < ColsPerScan; ++c) {
        double d = computeDistanceFor(s, c);
        if (d < 100.0) {
            matches.push_back(Match{s, c, d});
            std::cerr << "push: s=" << s << " c=" << c << " d=" << d << "\n";
        }
    }
}

Patterns to use depending on intent

  • Want the single best column per scan? Track a per-scan best (local variable), update during the inner loop, then push exactly one entry after that inner loop finishes.
  • Want the top N matches globally? Collect all candidates with their distances, then sort with std::sort and a comparator that orders by distance (or column) before reading the first N.

Final troubleshooting tips

  • Verify vectors are cleared/reinitialized at the expected points so elements don’t accumulate across unrelated runs. Confirm both parallel vectors (scan and col) are pushed together so their indices correspond. If logs still disagree with expectations, run under sanitizers (ASan) or valgrind and enable STL debug checks (e.g. _GLIBCXX_DEBUG) to detect out‑of‑bounds or memory corruption.

Recommended Answers

All 4 Replies

1) when using vectors you can access individual elelements just as you would do with a simple int array B = LiDARGrid.ConcentricScans.[scancounter].getColumn(concentriccol); Otherwise, this works. Your problem is probably something other than push_back

#include <vector>
#include <iostream>
using namespace std;

int main()
{
vector<double> Saved;
for(int i = 0; i<10; i++)
{
    if( (i%2) == 0)
        Saved.push_back(i);
}
vector<double>::iterator it;
for(it = Saved.begin(); it != Saved.end(); it++)
{
    cout << *it << "\n";
       
}


}

1) when using vectors you can access individual elelements just as you would do with a simple int array B = LiDARGrid.ConcentricScans.[scancounter].getColumn(concentriccol);

except that it doesn't check bounds

except that it doesn't check bounds

at() and [] both throw exceptions on out-of-bounds, at least it does with VC++ 2008 Express.

[edit]Nope, I'm wrong. Adding try/catch block the at() will throw and exception, but [] will just simply crash. But this is not relevent if the coder doesn't use try/catch blocks.[/edit]

An example is (0) is 0 and (1) is also 0. Then (0) is 19 and (1) is 16!!! Weird, eh?

Just guessing .. could it be that you actually do the 'offending' loop twice or more without clearing the vectors' content in between?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.