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 8 years ago.
Improve this question
I'm having a very nooby problem.
void update(node city, int costpath) {
int i;
for (i = 1; i < city.concity.size(); i++) {
city.costcity[i] = city.costcity[i] + costpath;
}
// Updates the sorrounding paths with the cost path of the previous one
}
node is a struct. It has vectors concity and costcity. When I call this function to update the values in the main, it doesn't work! When I print it out, it still shows the same old values…
Two problems:
void update(node city, int costpath) {
// ^^^^ 1) You're taking your node by-value. So it's a copy
// Internal to this function, you're just modifying the local city
int i;
for (i=1;i<city.concity.size();i++) {
// ^^^ 2) C++ is zero-indexed, so this loop skips the first element
The correct implementation would be:
void update(node& city, int costpath) {
for (int i = 0; i < city.concity.size(); ++i) {
city.costcity[i] += costpath;
}
}
C and C++ pass parameter by value when call function.
void update(node* city, int costpath) {
int i;
for (i=1;i<city->concity.size();i++) {
city->costcity[i] = city->costcity[i] + costpath;
}
}
See http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value
and http://clc-wiki.net/wiki/C_language:Terms:Pass_by_value
pass node city as a pointer or reference to the function.
c++ is 0 indexed thus start with 0 and increment till the array size.
void update(node& city, int costpath) {
or
void update(node* city, int costpath) {
and
for (int i = 0; i < city.concity.size(); ++i) {
Related
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 2 years ago.
Improve this question
I have the code below.
When I have main Run() function run the ResetTrackingTable() function. The ResetTrackingTable() calls 0 for my_n_rows and my_n_cols instead of accessing the existing numbers stored in the private member data.
Why is that? It seems like it's making a new instance of the function...
public:
WordGame();
void Run(Board &gameBoard, Trie &library, int wordlengthlim);
void CheckNode(int row, int col, Board & gameBoard, Trie &Library);
void ExitNode();
void ResetTrackingTable(int rows, int cols);
void PrintWordList();
private:
std::vector<std::string> my_WordList;
int my_wordlength;
int my_wordlengthlimit;
std::stringstream currentword;
int my_n_cols;
int my_n_rows;
std::vector<std::vector<bool>> my_TrackingTable;
};
void WordGame::Run(Board & gameBoard, Trie &Library, int wordlengthlim)
{
//std::stringstream word;
//std::string tempword;
//word.str("");
currentword.str(""); //Clear current word
int my_wordlengthlimit = wordlengthlim; //Import limit word length
int my_wordlength = 0; //Set current word length
int my_n_rows = gameBoard.numRows(); //Import number of rows
int my_n_cols = gameBoard.numCols(); //Import number of cols
for (int i_row = 0; i_row < my_n_rows; ++i_row)
{
for (int i_col = 0; i_col < my_n_cols; ++i_col)
{
//Actually, when should it be reset?
this->ResetTrackingTable(); //Initialize the tracking table as all false before each new starting char.
CheckNode(i_row, i_col,gameBoard,Library); //Check each beginning node.
}
}
}
void WordGame::ResetTrackingTable()
{
for (int i_row = 0; i_row < my_n_rows; ++i_row)
{
my_TrackingTable.push_back(std::vector<bool> {false});
for (int i_col = 1; i_col < my_n_cols; ++i_col)
{
my_TrackingTable[i_row].push_back(false); //Initialize the tracking table as all false.
}
}
}
These lines of code:
int my_n_rows = gameBoard.numRows(); //Import number of rows
int my_n_cols = gameBoard.numCols(); //Import number of cols
are declaring new variables inside the Run function.
If you want to refer to the member variables instead, drop the int declarator:
my_n_rows = gameBoard.numRows(); //Import number of rows
my_n_cols = gameBoard.numCols(); //Import number of cols
You need to do this for all your member variables that you want to use.
Also, your declaration:
void ResetTrackingTable(int rows, int cols);
doesn't match its definition:
void WordGame::ResetTrackingTable() { // ...
you need to have the same number of parameters of the same type.
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
struct Dates
{
int day;
int month;
int year;
}accountinfo[3];
struct Accounts
{
string name,lastname;
int number;
float balance;
}account[3];
void sortduetoaccnumbers()
{
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
if (account[j].number>account[j+1].number)
{
//swap
}
}
}
}
void sortduetodates()
{
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
if (accountinfo[j].year>accountinfo[j+1].year)
{
//swap
}
else if (accountinfo[j].year==accountinfo[j+1].year)
{
if (accountinfo[j].month>accountinfo[j+1].month)
{
//swap
}
else if (accountinfo[j].month==accountinfo[j+1].month)
{
if (accountinfo[j].day>accountinfo[j+1].day)
{
//swap
}
}
}
}
}
}
I can not sort these accounts using sorting algorithms. It crashes if I enter them. cmd stops suddenly and finishes the program.
I entered a comment line where swapping functions have to go. So you can analyze the code.
Every other functions are working except this one. I'm stuck at this point.
this code is wrong:
if (accountinfo[j].year>accountinfo[j+1].year)
because if j==2, then j+1=3 - index over array size => undefined behavior (and crash in your case)
you need to change loop condition to j<2 or rewrite your checks
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 5 years ago.
Improve this question
Check the following code:
#include<iostream>
using namespace std;
class example
{
public:
int number;
example()
{
cout<<"1";
number = 1;
}
example(int value)
{
cout<<"2";
number = value;
}
int getNumber()
{
cout<<"3";
return number;
}
};
int main()
{
example e;
e = 10;
cout<<e.getNumber();
return 0;
}
What is the output of the above code. Also, I want to know what happens when an object is directly assigned to a value. How will the compiler interpret it?
first you typed
example e;
So first constructor called and 1 printed
example()
{
cout<<"1";
number = 1;
}
output :
1
then you typed :
e=10 its equal to e = example(10); so another constructor called :
example(int value) /// beacause you used example(10)
{
cout<<"2";
number = value;
}
so your output is :
12
and number is 2
Finally in :
cout<<e.getNumber();
3 is couted but in the other hand value is `10`
because number = value your number is 10
So in Finally your output is :
12310
thanx for #StoryTeller for editting explaintions
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 7 years ago.
Improve this question
So lets say I have a struct like this:
struct example_structure
{
int thing_one;
int thing_two;
};
I also have an empty array which I am trying to fill with these structs. I am trying to add them as follows, but it doesn't seem to be working:
array[i].thing_one = x;
array[i].thing_two = y;
Instead of this is there a way to declare a variable of type example_structure and then add that to the array?
Use vectors. They can expand as needed.
#include <iostream>
#include <vector>
int main()
{
struct example_structure
{
int thing_one;
int thing_two;
};
std::vector<example_structure> data;
for (int i = 0; i < 3; i++)
{
data.push_back({i, i * 2});
}
for (const auto& x : data)
{
std::cout << x.thing_one << " " << x.thing_two << "\n";
}
}
Live example:
http://ideone.com/k56tcQ
You can write simply
array[i] = { x, y };
Or you can have a separate variable of the type of the structure. For example
struct example_structure obj = { x, y };
array[i] = obj;
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
I just came from C to C++ and find difficulties with compare string method.
I have a simple task. I need to create a class of school Teachers, then make an object array, and after withdrow all Teachers, who's subject is similar to testSubject.
So here is my class
class Teacher
{
private:
string FamilyName;
string Name;
string Patronymic;
string sex;
int exp;
std::string subject;
string speciality;
int age;
public:
Teacher();
int getExp();
string getSubject();
int getAge();
void show();
};
And here is my func, that withdrow the list of Teachers, teaching the input subject
void ListTeacherSub (Teacher spis[], int n)
{
//List of teachers, who's subject is like testSubject
std::string testSubject;
cout<<"Enter test subject "; cin>>testSubject;
for (int i=0; i<n; i++)
{
if (spis[n].getSubject().compare(testSubject) == 0)
spis[i].show();
}
}
Here it is main() function
int main()
{
Teacher *spis;
int n;
cout<<"Enter numbers of student "; cin>>n;
spis = new Teacher[n];
for (int i=0; i<n; i++)
{
spis[i].show();
}
ListTeacherAge(spis, n);
ListTeacherEx(spis, n);
ListTeacherSub(spis, n);
delete[] spis;
return 0;
}
So, everything is working nice, but when program reaches ListTeacherSub(spis, n) it is stops working. I used to work with strcmp only, but it doesn't works with string, as I understood.
So I decided to look for different realizations, and found that one http://www.cplusplus.com/reference/string/string/compare/
How can i fix my problem?
This
if (spis[n].getSubject().compare(testSubject) == 0)
should be
if (spis[i].getSubject().compare(testSubject) == 0)
This is incorrect (and causes undefined behaviour as it going beyond the end of the array):
if (spis[n].getSubject().compare(testSubject) == 0)
as it using n and not the loop counter i.
Other:
always check the result of input operations to ensure variables have been correctly populated and subsequent code is not using uninitialised or stale values:
if (std::cin >> n)
{
spis = new Teacher[n];
}
prefer to avoid explicit dynamic memory management. In this case std::vector<Teacher> would be suitable:
if (std::cin >> n)
{
std::vector<Teacher> spis(n);
for (Teacher& t) t.show();
}
Pass spis by const Teacher& to functions to avoid copy (and the parameter n is now superfluous).
std::string instances can be compared using ==.