Cannot execute code after the loop in c++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm facing a problem in c++ that I don't understand.
this is my code:
auto DataArray = jvalue.at(U("data")).as_array();
std::cout << "Outside the loop, first output" << std::endl;
for (int i = 0; i <= 10; i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}
std::cout << "Outside the loop, second output" << std::endl;
Output:
Outside the loop, first output
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
Press any key to continue . . .
It seems the code stops after the loop reach its end.
But why?
But if I commented out the
//auto data = DataArray[i];
//auto dataObj = data.as_object();
it doesn't have a problem.
By the way I'm working on cpprest and get json object data from api.
The jvalue variable holds the result.
And if I try and catch the code:
try {
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}
catch (const std::exception& e) {
std::wcout << e.what() << std::endl;
}
the result is infinite loop with output: not an object.
Please help. Thank you.

I think you should use i < 10 instead i <= 10 in your loop:
for (int i = 0; i < 10; i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}
Your last iteration hasn't output inside the loop. It fails there, there is no DataArray[10] with 10 index
And much better is to use DataArray.size() instead i < 10
for (int i = 0; i < DataArray.size(); i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}

Related

How to fix problem with iterating through list if times using iterator? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Debugger sais there is an incompatible iterator.
How i can solve this.
What can cause the problem.
Here is my main code
for (std::list<std::chrono::duration<double, std::milli>>
::iterator it = road.get_times().begin()
;it!= road.get_times().end();it++,z++) //error incompatible iterator
{
*road::file << "Samochod z drogi " << road.get_lane_number() << " pojechal ";
switch (road.get_direction())
{
case'S':
*road::file << "prosto" << std::endl;
break;
case'L':
*road::file << "w lewo" << std::endl;
break;
case'R':
*road::file << "w prawo" << std::endl;
break;
}
*road::file << "Jego czas stania w kolejce wyniosl ";
avarage_time += it->count() / 1000;
*road::file << round(it->count() / 1000) << std::endl;
}
function road.get_times ()
std::list< std::chrono::duration<double, std::milli>> get_times()
{
return times;
}
get_times returns by value, which means that every time you call it you get a new list object. This is what happens in your for loop. You call it 2 times and you get two objects. You can't compare iterators from two different objects. To fix this create one object by calling get_times just once:
auto times = road.get_times();
for (auto it = times.begin(); it != times.end(); ++it, z++)
//...
You also might want to pause and consider if returning by value is the right approach. I can't answer that for you since I don't know what times is and what is the structure of your program.

Segmentation fault core dumped vector pointer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
void printTop5()
{
int counter = 1;
int x, y;
float civ;
cout << "Total no. of records available = " << pointVector.size();
cout << "Printing top 5 exploration destinations....";
sort(pointVector.begin(), pointVector.end(), ascendingCiv);
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
x = p1.getX();
y = p1.getY();
civ = p1.getCivIndex();
cout << counter << ")\t";
if (civ > 0)
{
cout << "Civ idx: " << civ << " ; at sector(" << x << "," << y < ")\n";
}
else
cout << "<No records available>";
}
}
bool ascendingCiv(const PointTwoD &d1, const PointTwoD &d2)
{
return d1.getCivIndex() > d2.getCivIndex();
}
When I run this function I get this fault whereby it says segmentation fault core dumped. Any idea? Heard its about some memory problem.
One issue is that you are not checking whether you actually have at least 5 elements in your vector:
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
If i is out-of-bounds of the vector, accessing pointVector[i] would invoke undefined behavior.
The loop condition can be changed to the following:
#include <algorithm>
//...
size_t loopEnd = std::min(pointVector.size(), 5);
for (size_t i = 0; i < loopEnd; i++)
{
PointTwoD p1 = pointVector[i];
The loop will either go up to the size of the vector or 5 elements, whichever is smaller.

Compile error when using std::cout between if/elseif statements [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I was wondering why I get a compile error when I try to use std::cout in between, say, an if statement and else if statement.
For example:
if (condition)
{body}
std::cout << "hello world" << std::endl;
else if (condition)
{body}
Gives the error
error: 'else' without a previous 'if'
Let me get this right first:
You want to execute the cout statement in between the conditional no matter whether the condition was met or not, i.e. no matter whether the body of the if got executed or not.
As previous commenters noted, you cannot place something between the end of scope of the if-block and the else keyword.
What about approaching this by splitting up the if-else-if block into two separate if-blocks:
if (condition1) {
body1
}
cout << "hello world" << endl;
if (!condition1 && condition2) {
body2
}
That's why indentation is important
if (condition)
{ body
std::cout << "hello world" << std::endl;
}
else if (condition)
{
body
}
In your code, cout is outsite the if block, so no more else is expected.
You cannot add any executable code between if and else if other than the enclosed body of the if and else if loops.
if (firstCondition)
{
/*code for firstCondition*/
//code anything here
}
//not here #######
else if (secondCondition)
{
/*code for secondCondition*/
//code anything here
}
Correct is:
if (condition)
{
std::cout << "hello world" << std::endl;
}
else if (condition)
{body}
That would be an option for you.
if (fistCondition)
{
/*code for fistCondition*/
std::cout << "hello first" << std::endl;
}
else if (secondCondition)
{
/*code for secondCondition*/
std::cout << "hello second" << std::endl;
}
If you wanna call the cout in any case between the first and second condition, then avoid the else keyword and apply two if statements.
if (fistCondition)
{
/*code for fistCondition*/
std::cout << "hello first" << std::endl;
}
std::cout << "posterior to first and prior to second if statement" << std::endl;
if (secondCondition && !firstCondition)
{
/*code for secondCondition*/
std::cout << "hello second" << std::endl;
}
In this case, && !firstCondition emulates an else keyword for your purpose.

Why is std:: move slower than copy? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Consider the following program. Why is move slower than copy? I thought that move semantics sped things up considerably when returning locals as rvalues from functions. Can you tell me why moving a large vector is slower than copying it. The benchmark for returning a shared_ptr is provided as a base case.
#include <iostream>
#include <vector>
#include <string>
#include <chrono>
using namespace std;
vector<int> getStringByCopy()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return v;
}
vector<int>&& getStringByMove()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return move(v);
}
shared_ptr<vector<int>> getStringByPointer()
{
shared_ptr<vector<int>> v = make_shared<vector<int>>();
for (int x = 0; x< 15000000;x++) v->push_back(x);
return v;
}
int main(int argc, const char * argv[]) {
// insert code here...
chrono::system_clock::time_point begin = chrono::system_clock::now();
vector<int> v = getStringByCopy();
chrono::system_clock::time_point end = chrono::system_clock::now();
cout << v[0] << "copy took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
vector<int>&& m = getStringByMove();
end = chrono::system_clock::now();
cout << m[0] << "move took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
shared_ptr<vector<int>> sp = getStringByPointer();
end = chrono::system_clock::now();
cout << (*sp)[0] << "pointer took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;
return 0;
}
The output is:
0copy took 437043
0move took 462803
0pointer took 394549
Your method that is supposed to return per copy already return per move. If you return anything that were allocated on the stack per value in a method and return it, then you get a automatic move.

micro optimisation in for loop c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Let's assume C++ for loop in the form of:
for(int i; i<10;i++)
So the integer needs to be allocated in the beginning and then increased at every step the as well as compared. So wouldn't it be faster to do something like that:
f or(int i; i++<10;)
since the variable doesn't need to be loaded into the storage again? espacially when making it volatile?
This little example code gave the same result for all the cases. Does the for loop get optimized anyway or am I missing something?
#include<iostream>
#include<ctime>
int main() {
time_t start,ende;
volatile int dummy = 1;
const int rep = 1000000000;
// Method 1
start = time(0);
for (int i = 0; i < rep; i++)
dummy = 1;
ende = time(0);
std::cout << "Method 1: " << difftime(ende,start)*1000 << " ms" << std::endl;
// Method 2
start = time(0);
for (int i = 0; i++ < rep; )
dummy = 1;
ende = time(0);
std::cout << "Method 2: " << difftime(ende,start)*1000 << " ms" << std::endl;
// Method 3
start = time(0);
for (volatile int i = 0; i < rep; i++)
dummy = 1;
ende = time(0);
std::cout << "Method 3: " << difftime(ende,start)*1000 << " ms" << std::endl;
}
OS: Linux
Compiler: g++
Optimization: standart (no flag)
Compilers are a lot smarter than you think. They won't produce the kind of spurious load that you think they do.
Optimization depends on compiler and its options.
I'd suggest you to disassemble your code and see what's the result of the optimization.
A simple good disassemble e.g. HT editor or IDA version 5 (it free now). For small piece of code it will be easy enough.