It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I feel so lost trying to figure this out. I have my own data structure that I am planning on using vectors to avoid having to keep track of free space and reorginization that I would need to do if I used a simple array. I don't don't know if I'm just not initializing properly or what, but every assignment I do seems to just disappear into thin air.
Here is some simple code to illustrate what I'm talking about:
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int test_int;
bool test_bool;
};
struct file
{
vector<node> test_file;
};
int main()
{
file myfile;
int myint;
cout << "Enter number: ";
cin >> myint;
myfile.test_file[0].test_int = myint;
cout << "Number entered is: " << myfile.test_file[0].test_int << endl;
return 0;
}
So basically it is a vector inside a struct. It seems that the normal ways to access a vector don't seem to work, as in I can't read or write anything to the vector however things like myfile.test_file.size() seem to work (as in they return a '0' from a freshly created struct). Trying to access the index directly by myfile.test_file[0].test_int results in a runtime error of vector subscript out of range as if it isn't actually there.
Am I not initializing it properly? This seems kind of ridiculous to me and I can't understand why it wouldn't work that way.
Edit:
Edited code to more clearly show behavior I'm referring to. This compiles but gives a runtime error vector subscript out of range
The edited version doesn't work because you're accessing an element past the end of the vector:
myfile.test_file[0].test_int = myint;
Before you can do this, you need to either resize() the vector, or add an element using push_back():
myfile.test_file.push_back(node());
myfile.test_file[0].test_int = myint;
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to return multiple values in C++ and I have this snippet of code:
struct returns
{
int row_locs, col_locs;
int row_descriptors, col_descriptors;
double **locs;
double **descriptors;
};
void returns (int &row_locs, int &col_locs, int &row_descriptors, int &col_descriptors, double **locs, double **descriptors)
{
//make some changes in variables
}
The question is "What consumes more time : struct or call by reference?"
The difference is negligible in both cases. You shouldn't worry about these issues until you found them to be really issues. Short answer: do the way you like more and consider different aspects like how you will use the returned values later.
If you pass arguments by reference then they're already allocated on stack or dynamically and their pointed values are filled by the function. Time is spent in copying all the pointers to the stack and in storing at their addresses in called function.
In the second case the whole struct is allocated on stack and filled (probably by a single constructor that is missing in your struct). Time is spent in constructing the object onto the stack and in filling its values.
When function returns something bigger than long (on x86 and other 32 bit processors) or long long (on x86_64 and another 64 bit architectures) it returns pointer to alocated memory and then data is being copied to local structure.
struct example
{
long long a,b,c;
};
example create_new_struct(void)
{
example tmp; //new object is created
tmp.a = 3;
tmp.b = 4;
bmp.c = 5;
return example; //in low-level pointer is returned and all data copied
}
void modify_existing_structure(example & tmp)
{
tmp.a = 3; //setting data directly
tmp.b = 4;
tmp.c = 5;
return;
}
int main(void)
{
example a = create_new_struct(), b; //varaibles are being copied
modify_existing_structure(b); //variables are being set directly
return 0;
}
So you definitly shoud use references. But (as was noticed) your code makes zero sense. You shoud not use anonymous structures and parse all variables separated. In your code you create six pointers instead of one for each function call.
Also, I think you shoud learn more about object-oriented programming.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm wondering how to load a number of images in a function and assign it to one variable so i can call on them and also hold information for those images.
For example :
src = tile1.png
x = 10
y = 11
What kind of data type would i need ?
My goal is to loop through lines in a text file, load each image with its relevant information so the images are pre-loaded and ready to be displayed on the screen. I just a little stuck on how it would be done.
If you want to roll your own system, you could make an abstract base Image class. Then create a concrete sub-class for each image type you want to handle (e.g. ImageJpeg, ImagePng). These concrete sub-classes can then be simple wrappers around an image-loading library like libjpeg or libpng. Have a factory-function that create a concrete object but returns a std::shared_ptr of the abstract class. These can the be stored in standard container such as std::vector.
There are however already many existing image libraries, both specific (like libjpeg/libpng mentioned above) and generic (like SDL_Image or Boost GIL). Some of them have already C++ classes, some does not so need to be wrapped by you.
A struct.
example:
#include <iostream>
#include <string>
using namespace std;
struct a_new_datatype{
string name;
int age;
char gender;
};
int main(){
a_new_datatype my_own_datatype;
my_own_datatype.name = "Christopher";
my_own_datatype.age = 34;
my_own_datatype.gender = 'M';
cout << "Name: " << my_own_datatype.name << endl;
cout << "Age: " << my_own_datatype.age << endl;
cout << "Gender: " << my_own_datatype.gender << endl;
return 0;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I've been reading the Boost C++ documentation and trying to figure out how to generate a random real number between 0 and 1, using the uniform_01 part of the library. Does anyone have any suggestions?
Based on suggestions, I'm using this code, but it generates the same random value every time.
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
for (int i = 0; i < 10; i++) {
cout << random01(generator) << endl;
}
return 0;
}
Sorry if I wasn't clear; this question isn't solved, by my answer or any other. It's still generating the same random value each time.
There are a few 'gotcha's in this code:
The random01() function does not take a reference to the generator, but rather a copy of the generator. So if you call the function multiple times with the same generator - it will produce the same value over and over again!
The static uniform_01 in random01() only gets initialized on the first call to random01, so if it is ever called with a different generator, it will not use it, but rather use a reference to the first generator, which may even have been destroyed, since!
Correct would be something like following (note the & in the arguments list, for pass-by-reference, and the lack of static:
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
This is the solution I found:
#include <iostream>
#include <ctime>
#include <boost/random.hpp>
using std::cout;
using std::endl;
using boost::mt19937;
using boost::uniform_01;
double random01(mt19937 generator)
{
static uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
cout << random01(generator) << endl;
}
The code is slightly modified from here; hat tip to Bojan Nikolic.
I posted this as a "solution" in the hope that it helps someone, but please criticise anything you notice wrong with it. I tried to separate the seeding step from the actual generation so the twister isn't seeded every single time it generates a value.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
This is probably a basic question.
I have a vector of a data type 'player' that I have defined myself using a struct:
struct player {
string player_name;
string label;
...
...
}
I then having a function taking a vector of these player data types as a parameter and I want to access the members in the struct i.e.
void foo(vector<player> players) {
cout << players.at(0).player_name;
}
The at(i) works because it is a function of vector. However, I can't access player_name. Why is this and how can I solve it? Apologies if this is basic and boring.
Following code accesses player in vector:
#include <string>
#include <vector>
using namespace std;
struct player {
string player_name;
string label;
};
int main() {
vector <player> p;
p.push_back( player() );
p.at(0).player_name = "fred";
}
Your problem is that foo() returns but you don't see the side-effect of the changed player_name, I guess?
It's because you've passed the vector to foo() by value rather than reference. foo() is operating on a copy of the vector rather than whatever original you passed to it, so the player_name change is lost when the function ends.
Try changing the function signature to void foo(vector<player>& players).
(Note that I've added an ampersand to make the parameter a reference.)
You should not get a compilation error since the code you posted is fine. If you are getting a runtime-error make sure you have inserted at least one object into the vector before you try to access it.
just speculation
if you get a compile error:
probably you declare a class instead of a struct.
if you get a runtime error:
the vector is empty
no error but not result:
you haven't flush the stream. Add std::endl or call std::cout.flush()
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
int main()
{
char *fp = "Alex";
cout<<fp <<" "<<(void*)fp<<endl;
*(fp+1) = 'p';
cout<<fp <<" "<<(void*)fp<<endl;
}
You modified a string literal. That's undefined behavior.
Increase the warning level on your compiler, you want a warning/error for the line char *fp = "Alex";, because it creates a non-const pointer to immutable data. It's only allowed in C++ for compatibility with C, and it's a misfeature there too.
I don't really like answering "questions" like this, but here is an obvious error:
*(fp+1) = 'p';
fp points to readonly memory as you assigned a string literal to it. Thus, you cannot modify what fp points to. If you want to modify the string declare fp as a char[] so that it will be allocated on the stack.
I'm going to have to assume that you are talking about the following compiler warning:
prog.cpp: In function ‘int main()’:
prog.cpp:5: warning: deprecated conversion from string constant to ‘char*’
Next time please tell us in the question why it is that you think something is "wrong".
As the warning states, converting string constants to char*, whilst fairly normal in C, is deprecated in C++.
Do this instead:
#include <iostream>
using namespace std;
int main() {
char const *fp = "Alex"; // <--- `const` here
cout<<fp <<" "<<(void*)fp<<endl;
*(fp+1) = 'p';
cout<<fp <<" "<<(void*)fp<<endl;
}
You will then find that your statement *(fp+1) = 'p' does not compile. That is because of the const; in fact, the lack of const in your original code merely hid the fact that you may not modify the underlying data of that string literal.
You should copy the characters to a new buffer that your program owns. You can do this neatly using std::string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fp = "Alex";
cout << fp << " ";
fp[1] = 'p';
cout << fp << " ";
}
In general, use std::string wherever you can. There is rarely a reason to avoid the features of the C++ Standard Library.