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;
Related
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 1 year ago.
Improve this question
I got the homework,i try to solve it,but i dont know why its bad.
One of part of this code was a default:
#include <iostream>
using namespace std;
/*##SOLUTION##*/
/*##SOLUTION##*/
int main()
{
Valami var;
int i=var.ujszam();
cout<<i<<endl;
cin>>i;
var.tarol(i);
var.print();
return 0;
}
I have to to supplement this code with some criterion.
I have to create Valami class after that I have to create ujszam method which is get the integer number and give it back.
I have to create tarol method which is save the Integer number.
and finally i have to create print method which is display the saved number.
The input -2 and 72,the result gonna be -2 and "A szam : 72"
Here is my attempt:
class Valami
{
public:int tarol;
public:int ujszam()
{
int i;
cin>>i;
return i;
}
public:void tarol(int ertek)
{
tarol=ertek;
}
public:void print()
{
cout << "A szam : " <<tarol<< endl;
}
};
I try to fix it some many ways,but idk what is the problem.
tarol is used as name of both a variable and a function. You have to give another name to one of them.
example:
class Valami
{
public:int tarol_var; // rename the variable
public:int ujszam()
{
int i;
cin>>i;
return i;
}
public:void tarol(int ertek)
{
tarol_var=ertek; // rename the variable
}
public:void print()
{
cout << "A szam : " <<tarol_var<< endl; // rename the variable
}
};
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 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) {
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 9 years ago.
Improve this question
I'm writing a program of a stock market where I read from a file and sort with symbols and percent gain/loss. I have completed sorting with symbols but having trouble establishing the percent gain loss. Basically i am instructed to use vectors. We are required to produce the list ordered by percent gain/loss and i need to sort the stock list by this component. However i'm not to physically sort the list by component percent gain/loss; instead provide a logical ordering with respect to this component.
so basically i added a data member, a vector to hold the indices of the stock list ordered by the component percent gain/loss. i called it array indexByGain. so when i print the list ordered by the percent gain/loss, i use the array indexByGain to print the list. my problem is an i need help on how to start if someone could show me an example or explain on how to go about this i can continue or correct me on my rough draft that will be helpful. below is a rough draft of my code. stockType has to do with the where data is stored from the file.
#include <iostream>
#include "stockType.h"
class stockListType
{
public:
void sortBySymbols();//sort out symbols and it comiples correctly.
void sortByGain();
void printByGain();
void insert(const stockType& item);
private:
vector<int> indexByGain;//declared a vector array indexByGain..
vector<stockType> list;
};
void stockListType::insert(const stockType& item)
{
list.push_back(item)//inserts the data from file to vector array.
}
//function prints out the gain
void stockListType::printByGain()
{
//my code to print out the gain..
}
//function to sort the gain and this is where i am stuck.
void stockListType::sortGain()
{
int i, j, min, maxindex;
for(i=0;i<list.size();i++)
{
min = i;
for(j=i+1;j<list.size();j++)
list[maxindex].getPercentage()<list[j].getPercentage();
maxindex = j;
indexGain.push_back(maxindex);
}
I know I am wrong but am i starting on a good base or totally of. please you could assist me or correct me. Thanks. oh sorry before i forget getPercentage() calculates and returns the percentage gain/loss.
Initialize the index and use std::sort:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
struct Data {
int value;
int percent;
};
typedef std::vector<Data> DataVector;
typedef DataVector::size_type size_type;
typedef std::vector<size_type> IndexVector;
DataVector data { { 1, 1 }, { 2, -2 }, { 3, 3 }, { 4, -4 }, { 5, 5} };
IndexVector index;
index.resize(data.size());
for(size_type i = 0; i < data.size(); ++i) {
index[i] = i;
}
struct Less
{
const DataVector& data;
Less(const DataVector& data)
: data(data)
{}
bool operator () (size_type a, size_type b) {
return data[a].percent < data[b].percent;
}
};
std::sort(index.begin(), index.end(), Less(data));
for(size_type i = 0; i < index.size(); ++i) {
std::cout << data[index[i]].value << ": " << data[index[i]].percent << std::endl;
}
}
You may use C++11:
std::sort(index.begin(), index.end(),
[&](size_type a, size_type b) { return data[a].percent < data[b].percent; }
);
for(auto i: index)
std::cout << data[i].value << ": " << data[i].percent << std::endl;
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 have this code where it read user code and store it on array, and later find sums of elements on each array and compare both of them, the code is as follows:
#include <iostream>
#include <vector>
#include <numeric>
typedef std::vector<int> int_vec_t;
//Call by reference to set variables in function
void readData(int_vec_t& v1, int_vec_t& v2)
{
v1 = int_vec_t{1,1,8}; //This only works for C++11
v2 = int_vec_t{2,2,2};
}
void readUserData(int_vec_t& v)
{
for(;;)
{
int val;
std::cin>>val;
if(val == 0) break;
v.push_back(val);
}
}
int main()
{
using namespace std;
int_vec_t A;
int_vec_t B;
readData(A,B);
//Or
readUserData(A);
readUserData(B);
int sumA = accumulate(A.begin(), A.end(), 0); //Then use iterators
int sumB = accumulate(B.begin(), B.end(), 0);
cout << ((sumA > sumB) ? "Array A Greater Than Array B\n" : "Array B Greater Than Array A\n");
return 0;
}
But the above code generate following errors:
test.cpp: In function ‘void readData(int_vec_t&, int_vec_t&)’:
I am using g++ test.cpp -o test to compile the code. What am I missing here?
don't you think the compilation should be something like:
$ g++ -std=c++11 test.cpp -o test ?
it keep taking inputs, how can i limit it to take only 5 elements per array
void readUserData(int_vec_t& v)
{
for(int i = 0; i < 5; i++)
{
int val;
std::cin>>val;
// if(val == 0) return;
v.push_back(val);
}
}
Great thanks, in between the loop how can out put statement so that user knows he is entering array for array 1 and after that array 2?
void readUserData(int_vec_t& v, std::string default = "")
{
for(int i = 0; i < 5; i++)
{
int val;
std::cout << "Enter for "<< default << "[" << i << "]: ";
std::cin>>val;
// if(val == 0) return;
v.push_back(val);
}
}
And from your main() you can send in a different string.
for example like this:
readUserData(A, "A");
readUserData(B, "B");
This was my code posted as a suggested solution to
c++ passing function into main error
Yes it needs a C++11 compiler as stated in the code. It was never meant as final code either.
I would recommend the OP to read a good book about C++. Let me suggest "C++ The Programming Language" http://www.amazon.com/The-Programming-Language-3rd-Edition/dp/0201889544