I'm trying to read pairs values from a file in the constructor of an object.
The file looks like this:
4
1 1
2 2
3 3
4 4
The first number is number of pairs to read.
In some of the lines the values seem to have been correctly written into the vector. In the next they are gone. I am totally confused
inline
BaseInterpolator::BaseInterpolator(std::string data_file_name)
{
std::ifstream in_file(data_file_name);
if (!in_file) {
std::cerr << "Can't open input file " << data_file_name << std::endl;
exit(EXIT_FAILURE);
}
size_t n;
in_file >> n;
xs_.reserve(n);
ys_.reserve(n);
size_t i = 0;
while(in_file >> xs_[i] >> ys_[i])
{
// this line prints correct values i.e. 1 1, 2 2, 3 3, 4 4
std::cout << xs_[i] << " " << ys_[i] << std::endl;
// this lines prints xs_.size() = 0
std::cout << "xs_.size() = " << xs_.size() << std::endl;
if(i + 1 < n)
i += 1;
else
break;
// this line prints 0 0, 0 0, 0 0
std::cout << xs_[i] << " " << ys_[i] << std::endl;
}
// this line prints correct values i.e. 4 4
std::cout << xs_[i] << " " << ys_[i] << std::endl;
// this lines prints xs_.size() = 0
std::cout << "xs_.size() = " << xs_.size() << std::endl;
}
The class is defined thus:
class BaseInterpolator
{
public:
~BaseInterpolator();
BaseInterpolator();
BaseInterpolator(std::vector<double> &xs, std::vector<double> &ys);
BaseInterpolator(std::string data_file_name);
virtual int interpolate(std::vector<double> &x, std::vector<double> &fx) = 0;
virtual int interpolate(std::string input_file_name,
std::string output_file_name) = 0;
protected:
std::vector<double> xs_;
std::vector<double> ys_;
};
You're experiencing undefined behaviour. It seems like it's half working, but that's twice as bad as not working at all.
The problem is this:
xs_.reserve(n);
ys_.reserve(n);
You are only reserving a size, not creating it.
Replace it by :
xs_.resize(n);
ys_.resize(n);
Now, xs[i] with i < n is actually valid.
If in doubt, use xs_.at(i) instead of xs_[i]. It performs an additional boundary check which saves you the trouble from debugging without knowing where to start.
You're using reserve(), which increases capacity (storage space), but does not increase the size of the vector (i.e. it does not add any objects into it). You should use resize() instead. This will take care of size() being 0.
You're printing the xs_[i] and ys_[i] after you increment i. It's natural those will be 0 (or perhaps a random value) - you haven't initialised them yet.
vector::reserve reserve space for further operation but don't change the size of the vector, you should use vector::resize.
Related
int numRows = 5;
string s ="hellohi";
vector<string> rows(min(numRows, int(s.size())));
I think it is using the fill constructor. https://www.cplusplus.com/reference/vector/vector/vector/
but I don't know it creates a vector of NULL string or a vector of an empty string ?
And what is the size of the NULL ?
And what is the size of the empty string? 1 bytes ("/0"char) ?
The constructor you're using will create empty strings. For example you can check with:
// check the number of entries in rows, should be 5
std::cout << rows.size() << std::endl;
// check the number of characters in first string, should be 0
std::cout << rows[0].size() << std::endl;
// now the size should be 11, since there are 11 entries
rows[0] = "hello world";
std::cout << rows[0].size() << std::endl;
I believe the size of NULL is implementation defined, you could find it with:
std::cout << sizeof(nullptr) << std::endl;
I get 8 as the size (which is 64 bits)
Similar to the nullptr, the size of an empty string is probably also implementation defined, you can find it like:
std::string test_string;
std::cout << sizeof(test_string) << "\n";
std::cout << test_string.size() << "\n"; // should be 0 since the string is empty
test_string = "hello world"; // it doesn't matter how long the string is, it's the same size
std::cout << sizeof(test_string) << "\n";
std::cout << test_string.size() << "\n"; // should be 11 since the string has data now
I get 32 bytes for the size. The reason the size of the string doesn't change is due to how it works behind the scenes, instead of storing data (most of the time) it only stores a pointer to the data (which is always a fixed size).
I am building a 2d game and I am storing all my enemy objects in an array. Right now I am trying to implement a quadtree. Currently I am just trying to build the quadtree and am not concerned with collisions. The code that pushes items to the quadtree is the following :
for (std::vector<Enemy>::iterator i=m_enemies.begin(); i != m_enemies.end(); ++i) {
std::cout << &(*i) << "Address of the object" << std::endl;
m_quad.Insert(&(*i));
}
The code for the Insert is the following :
void Quad::Insert(sf::RectangleShape* l_gameObject){
std::cout << &l_gameObject << "dsa1" << std::endl;
std::cout << "called insert " << m_objects.size() << std::endl;
m_objects.push_back(l_gameObject);
if (m_level < m_maxLevel) {
if (m_objects.size() > 3) {
std::cout<< "creating subregions " << m_objects.size() << std::endl;
m_subRegions.push_back(Quad(m_x,m_y,m_width/2.f, m_height/2, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x+m_width/2.f,m_y,m_width/2.f,m_height/2.f, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x+m_width/2.f, m_y + m_height/2.f, m_width/2.f, m_height/2.f, m_level + 1, m_maxLevel-1));
m_subRegions.push_back(Quad(m_x, m_y + m_height/2.f, m_width/2.f, m_height/2.f, m_level + 1, m_maxLevel-1));
std::vector<int> temp;
for (int i=0; i < m_objects.size(); i++){
for (int j=0; j< m_subRegions.size(); j++) {
if (m_subRegions[j].Contains(m_objects[i])) {
m_subRegions[j].Insert(m_objects[i]);
temp.push_back(i);
break;
}
}
}
for (int i = temp.size(); i > -1; i--){
m_objects.erase(m_objects.begin() + temp[i]);
}
}
}
}
When I print the address that I am passing to the Insert function and the one I have in the function I see that they are different. In fact the on in is always the same and the one I pass is always different as it should be. Could anyone clarify why that is the case ?
EDIT : Thanks to gsamaras for pointing out that I was printing the address of the parameter.
Followup question
When I use the methods of the object I am addressing in the first for loop I get the correct results, but when I do the same thing in the Insert function I get 0. Why is that ?
You are printing the address of the address.
Change this:
std::cout << &l_gameObject << "dsa1" << std::endl;
to this:
std::cout << l_gameObject << "dsa1" << std::endl;
in order to print the same thing as outside your of your function.
Inside Insert, you're printing the address of the parameter.
Outside Insert, you're printing the parameter's value.
You want
std::cout << l_gameObject << "dsa1" << std::endl;
since l_gameObject is the address you're passing in.
I am having a hard time parsing an edge list from a text file in c++. The edge list is in the following format:
*Edgeslist
1 6487
2 6488 6489 6490 6491 6492 6493 6494 6495 6496
3 6497 6498 6499 6500 6501 6502 6503 6504 6505
4 6506 6507 6508
5 6509 6510 6511
6 6512 6513 6514 6515
7 6516
8 6517 6518
9 6519 6520
10 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
11 6566
My vector is a vector of structs that is defined here
struct Edge{
int character;
int edges[16];
};
The first number of each line should be read into the character integer and the rest should be read into the edges array. I have tried a few for loops, and currently working on a lengthy while loop with if statements for each number of possible integers to go into the array (max of 15 integers per line after the first number). Here is a part of my implementation so you can see what I am attempting.
while(std::getline(input, line))
{
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
std::stringstream ss(line);
if ( ss >> a)
{
std::cout << "1 " << a << "\n";
}
if ( ss >> a >> b)
{
std::cout << "2 " << a << " " << b << "\n";
}
if ( ss >> a >> b >> c)
{
std::cout << "3 " << a << " " << b << " " << c << "\n";
}
if ( ss >> a >> b >> c >> d)
{
std::cout << "4 " << a << " " << b << " " << c << " " << d << "\n";
}
I'll end it there but it does go on for awhile until it covers every possible line.
At the moment I am just trying to figure out the basic logic to parse this text file.
You have tagged this as C++.
I would recommend you add an initializer if you must continue with pod ...
struct Edge
{
int character;
int edges[16];
// more data attributes
// use ctor to initialize these values
Edge(void) :
character (0)
// edges[16]
{
for (int i=0; i<16; ++i)
edges[i] = 0;
}
// use dtor to clear them
~Edge(void)
{
for (int i=0; i<16; ++i)
edges[i] = 0;
character = 0;
// ...
}
};
I suspect you will also need a count of how many edges have currently been in installed (or perhaps call it nextIn).
The fundamentally important signature of C++ code is the preferred use of objects-defined-by-a-class. I recommend you consider:
struct Edge
{
int character; // poor name choice
std::vector<int> edges; // << use vector, not array
// use ctor to initialize these values
Edge(void) :
character (0)
// edges // default ctor does what you need
{
}
~Edge(void) {
// edges default dtor does what you need
character = 0;
}
};
The std::vector reduces your work to read arbitrary counts of values.
// Typical input:
// 3 6497 6498 6499 6500 6501 6502 6503 6504 6505
// 4 6506 6507 6508
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
struct Edge
{
int character; // <<< poor name choice
std::vector<int> edges; // <<< use vector, not array
// use ctor to initialize these values
Edge(void) :
character (0)
// edges default ctor does what you need
{
}
~Edge(void) {
// edges default dtor does what you need
character = 0;
}
bool ok(void) {
/*tbd - count errors? size check? */
return(true);
};
void load(std::string line)
{
// typical input line
// 3 6497 6498 6499 6500 6501 6502 6503 6504 6505
// 4 6506 6507 6508
std::stringstream ss(line+' ');
// padding at end ---------^----because ss.eof() sooner than I expected
//debug only
//std::cout << " in: (" << std::setw(3) << line.size() << ")
// << line << std::endl;
// process one work buff
do {
ss >> character; // read 1st int of line
if (ss.eof()) break;
if (ss.bad()) {
// maybe invalid integer format
std::cerr << "bad input: " << line << std::endl;
// tbd - error count?
break;
}
// process 1 or more entries for edge.vector from line
do {
int edgeVal = 0;
ss >> edgeVal;
if (ss.eof()) break;
if (ss.bad()) {
// maybe invalid integer format
std::cerr << "bad input: " << line << std::endl;
// tbd - error count?
break;
}
// additional edgeVal validations?
edges.push_back(edgeVal); // fill in one value to edge vector
// add validation here if edges.size() has an upper limit
// tbd - error count?
} while (1); // // process 1 or more entries to vector from line
} while(1); // one work buff
// debug only
dump();
} // void load(std::stringstream& ss, std::string line)
// for debug
void dump()
{
std::cout << "dump: (" << std::setw(3) << edges.size()
<< ") " << character << " ";
for (size_t i=0; i<edges.size(); ++i)
std::cout << edges[i] << " ";
std::cout << std::endl;
}
}; // struct Edge()
int t237(void)
{
std::vector<Edge> edgeVec;
// file processing at outer scope
do {
std::string line; // work buff
(void)std::getline(std::cin, line);
if(std::cin.eof()) break;
std::stringstream ss(line);
Edge temp; // a work buff
temp.load(line); // <<< load method for Edge (part of Edge)
// not sure where to put all the Edge objects
// temporarily, use edgeVec;
if (temp.ok()) // add flag check that edgeVec had no errors
edgeVec.push_back(temp);
else
/*tbd*/{}; // error in temp ... discard it? report it?
} while (1);
// tbd - how return vector and file status
return (0);
}
---- update
ss.eof() occurring before I expected ... added "padding at end"
added dump() debug method, added debug cout of input line
minimal testing complete
You should split your string into substrings at whitespaces. Details are explained here.
After that, you just cast your substrings to appropiate type.
std::stringstream ss(line);
ss >> character;
unsigned int n=0;
while(ss >> edges[n])
{
++n;
}
(One could make this a little shorter, but that would make it less readable.)
I have just started using range based for loops to simplify my code when using templates. I have come across a strange error and am not sure if this is something that I am missing or if the compiler is making a mistake. I have written a piece of code to illustrate the issue that I am having as well as the output. These are shown below.
Note: I am using the Mingw64 compiler on windows g++ (rev5, Built by MinGW-W64 project) 4.8.1 compiled without optimization with the --std=c++11 flag.
Code:
#include <iostream>
#include <array>
#include <vector>
int main()
{
// Declares an array of size 5 and of type int and intialises.
std::array<int,5> x = {1,2,3,4,5};
std::vector<int> y = {1,2,3,4,5};
// Prints each element
std::cout << "Array:" << std::endl;
std::cout << "x" << "\t" << "i" << std::endl;
for (auto i : x)
{
std::cout << x[i] << "\t" << i << std::endl;
}
std::cout << "Vector" << std::endl;
std::cout << "y" << "\t" << "i" << std::endl;
for (auto i : y)
{
std::cout << y[i] << "\t" << i << std::endl;
}
std::cin.get();
std::cin.get();
return 0;
}
Output:
Array:
x i
2 1
3 2
4 3
5 4
0 5
Vector
y i
2 1
3 2
4 3
5 4
1313429340 5
I would assume that the last line of both the vector and array output is an overflow, and notice how i starts at one instead of zero?? I would have assumed it would behave as described here.
I think you have not understood the syntax correctly
for (auto i : x)
here i is not an index of an array, it is the actual element inside the vector x.
So it is doing its job correctly.
"i" is the actual value in the array and not the index. So it is printing x[1] to x[5] in the first column and 1 to 5 in the second column. To access the values just print "i".
for (auto i : x)
creates copies of elements in x to be used inside your for loop. Use an iterator instead to access elements by their index.
for (size_t i = 0; i < x.size(); i++) {
std::cout << x[i] << "\t" << i << std::endl;
}
I was testing some code for a class that wraps a 2-dimensional array of structs.
WrapperClass x;
SomeStruct try1 = x.at(0, 0);
SomeStruct try2 = x.at('a', 1);
SomeStruct array[] = {try1, try2};
// There were originally 3 of these test variables above, but I forgot to
// change the loop upper bound when I deleted one
for (int i = 0; i < 3; i++) {
// I added this line after noticing the non-error
std::cout << &array[i] << '\n';
std::cout << array[i].property1 << '\n';
std::cout << array[i].property2 << '\n';
std::cout << array[i].property3 << '\n';
std::cout << "-\n";
}
return 0;
This outputs:
0x7ffdadface08
0
0
0
-
0x7ffdadface14
0
0
0
-
0x7ffdadface20
0
0
0
Why doesn't this code segfault with an "access out of bounds" error or something? I only created 2 structs in the array; why is there suddenly a third one that I can freely and safely access?
Because it's undefined behavior and anything can happen, including no immediate error. I suggest you use containers such as vectors which are bounds-checked by good debug compilers.