Cannot access member functions of vector<int> - c++

I've been attempting to figure out this bug for about an hour now. It's probably a really obvious syntax thing I'm overlooking. This is my first C++ project, and I don't have a good handle on the structure of the language.
Here's my header file:
#pragma once
#include <vector>
class BoardState
{
private:
std::vector<int> numbers;
int SIZE;
public:
BoardState();
std::vector<int> getState();
bool isZero();
};
And here's the implementation, in a separate file:
#include "BoardState.h"
BoardState::BoardState(){
SIZE = 4;
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(5);
numbers.push_back(7);
}
std::vector<int> BoardState::getState() { return numbers; }
bool BoardState::isZero() {
for (int i = 0; i < numbers.size(); i++) {
if (numbers[i] != 0) { return false; }
}
return true;
}
This code is really simple, so I have no clue what could be going wrong to produce the errors. However, on every method call, push_back and size, I am getting errors, saying that class "std::vector<int, allocator>" has no member "method_name_here".
My background is Java, so my first thought was that I wasn't able to call these methods because numbers is not initialized. However, any attempt I made to initialize numbers in the header file resulted in an error as well. I tried std::vector<int> numbers = { 1,3,5,7 };, I tried std::vector<int> numbers(4,0);, I even tried creating an array and constructing the vector from that. Not only did all those attempts cause errors, they also didn't fix the method calls either.
What am I missing? Do I need to initialize the vector, or is what I have in the header file enough? Any advice would be helpful here, since I can't find anything online about similar errors. I've even copy-pasted code from StackOverflow answers about similar problems, and that produced errors as well.
EDIT: I've pared down the code as much as possible while keeping the error:
#include <vector>
class BoardState
{
std::vector<int> numbers;
BoardState() { numbers.push_back(1); }
int getSize() {
int i = numbers.size();
return i;
}
};
On the line numbers.push_back(1);, my compiler underlines the token "push_back", and highlighting it reads:
class "std::vector<int, allocator>" has no member "push_back"
On the line int i = numbers.size();, the token "size" is underlined, and the error reads:
class "std::vector<int, allocator>" has no member "size"
I still have no clue what's going on.
Edit 2: Put the method calls into a constructor and a function. This changed the error message associated with push_back().
Edit 3: I have discovered something very disconcerting. This code works perfectly fine in a different compiler. I copy-pasted in the exact code from Edit 1 and it ran with no issues. I think the problem must be with Visual Studio rather than the actual code. Thank you all for helping me out with this. I think I'm just going to switch to a different compiler and hope for the best.
Edit 4: Just to prove to pm100 that my code is exactly as I've said, here's a screenshot from visual studio.
Here it is.
Aside from the main method, this is character-for-character what I've put in this question. I have a guess as to why this doesn't work, though. I modified my version of Visual Studio 2019 to run .386 assembly code for a college class. While I think I followed the guide to do that without affecting anything else, it may have screwed up parts of the C++ compiler.

I suggest that you could select Tools->Import and Export Settings->Reset all settings-> Visual C++ to restore the default settings.
If it does not work, you could reinstall VS.

Related

Undefined reference to function which is member of an another class

I'm building a simple application to solve sudoku puzzles. It's my first time creating something serious with C++, so I'm open for code style/structure critique.
The problem I bumped into has something to do with organizing multiple files.
I have two classes referencing each other using functions. When I try to call a function:
void Field::runColumnCheckout(CellGroup* sender, int cellRelativeX)
{
}
in a CellGroup class using an instance of Field class:
void CellGroup::runISC(int possibilityNumber)
{
for (int x = 0; x < 3; x++) {
int amountInColumn = 0;
for (int y = 0; y < 3; y++)
if (cells[x][y]->isPossible(possibilityNumber))
amountInColumn++;
if (amountInColumn > 1) {
//parentField is an instance of a Field class
//stored in a private field of the CellGroup class
parentField->runColumnCheckout(this, x);
return;
}
}
//...
}
An undefined reference occures. I don't quite understand, why.
All the examples were taken from cell_group.cpp and field.cpp that are defining classes from cell_group.h and field.h.
Unfortunately, I couldn't manage to put all the files in a question as they have gained a lot of lines, but you can look at them on my github.
I have found a similar question and another one, but they seem to have issue with the way they compile their files. I've had two referencing each other classes structured similarly before adding code I have problem with right now and everything compiled fine.
I'm compiling everything using GCC compiler on Windows and CodeBlocks as an IDE.
CodeBlocks somehow lost connection with field.cpp file or didn't add it creating file. Going and manually adding it to the project tree (even though it was already there) Project->Add files... solved the problem.
Thanks #Peter for finding the solution.

i64vec2 copy constructor suddenly starts corrupting stuff

Okay, I'm sorry. It seems that Visual Studio just goes crazy and the values are REALLY fine. As to why this happens and when, I have no idea.
There is a complete sample at the end, I'd like to know if it does this crazy thing for you as well. Try it with x86 and x64 builds and look at what the debugger says the value is.
Maybe this is a good thing though, now I won't miss needless copying.
I find this really odd. Whenever I copy a glm::i64vec2 it gets corrupted.
But if i do just this line:
glm::i64vec2 copy(glm::i64vec2(1, 1));
In my main, it just works.
I have deleted all object files and rebuilt the program from scratch.. any ideas what might be wrong?
The only one I can think of is that I have included headers in different order in different places and that somehow messed this up.
What I really should use here is const reference, but still this scares the crap out of me. One of these could easily stay hidden as a bug and cause lots of headache for me.
I just found another bug this caused. This time it happens inside a single class.
This fails, but the same works in main
bool test(glm::i64vec2 p_worldPos)
{
return p_worldPos.x == 1;
}
void QuadTree::getObjectsHitInPriority(glm::i64vec2 const & p_worldPos, std::vector<Object*> & p_objects)
{
test(p_worldPos);
Um, I don't know what this means, but the following observation has been made. In my program main.cpp this fails
#include <glm/glm.hpp>
#include <iostream>
struct whatthehell
{
bool test(glm::u64vec2 p_test)
{
return p_test.x == 1;
}
};
int main(int argc, char ** argv)
{
whatthehell hell;
if (hell.test(glm::u64vec2(1, 1)) == false)
{
std::cout << "What the hell\n";
}
return 0;
}
Ok, update. This works with x86 but not on x64 with my VS2015. Can anyone test this?

Visual Studio 2010 O2 optimization give wrong result?

int listenPort()
{
//if (server)
//{
// return server->port();
//}
//std::cout << server->port() << std::endl;
//return 0;
//add below 2 lines only to make it work right under Realease.
//std::fstream f("Z:/fsfasjlfjal.txt");
//f.close();
if (_listenPort != -1)
{
return _listenPort;
}
return 0;
}
I have one function named listenPort, variable _listenPort has been set to -1 in construct function, I want to check its value. When it changes return it or return 0.
I use Visual Studio 2010 to compile the code, DEBUG everything is OK. But when I change to Release(/O2), function always return 0. I tried add two lines code: fstream open and close. Now it seems everything is right.
But this solution is ugly, I just open and close some file. What should I do? Thanks.
One not recommended solution is to make replace int _listenPort; with volatile int _listenPort;. Read this to understand why this solution is not recommended.
A good solution would use synchronized writing and reading of _listenPort.
Or As I suggested before move definitions of class to a different file. This way, compiler won't inline your code and function will return expected value.
You're probably trying to run a debugger on an optimised (/O2) code and set breakpoints in your function. This is not going to work. Compiler is free to change order of your code as it sees fit, provided that the outcome of the code is the same as if it were untouched.
If you really want to test some values with optimised code, you need to log the values somewhere (a file) or print them out in the console.

if statement in main function c++

Okay, probably a dumb question to you guys but I can't figure it out.
So I'm taking a c++ basics course in class and so far I'm struggling/crying.
I can't show you guys my code because I'm not allowed/there are consequences if I'm caught but I could probably give a example.
I'm using xcode. So when I compile, I get two errors below (image provided).
I searched for similar questions, but those seem too complex compared to what I'm doing. In addition, the only includes I have are iostream and string.
I know the problem occurs when I add an if statement in my main function. I know this because when I delete it, everything compiles as expected. Yet when I add it again to the main function, these errors occur.
So my question is, based on what I know, is it proper to add an if statements whenever in the main function?
Below is an example. I wrote the functions below and called above.
#include <iostream>
#include <string>
using namespace std;
// example functions that I just made up to explain the structure of my actual code.
//Don't bother trying to understand it. It's just to explain that
//I wrote my functions at the
// bottom and called it at the top.
int getNumberofWins(param1, param2);
string getTheName(int player1);
int executeCycle(string p1_name, string p2_name);
void stateWinner(string winner_name);
int main {
playerOne = getTheName(1);
playerTwo = getTheName(2);
r1 = executeCycle(playerOne, playerTwo);
r2= executeCycle(playerOne, playerTwo);
totalWin1 = getNumberOfWins(1, r1, r2);
totalWin2 = getNumberOfWins(2, r1, r2);
cout << totalWin1;
//This is the where I get the errors. When I delete the if statement,
//Everything compiles. When I add it, an error occurs.
if (totalWin1 == 2){
stateWinner(playerOne);
}
return 0;
}
string getTheName(int player1){
string playerOne;
string playerTwo;
if(player_number == 1){ code code code
}
}
int getNumberofWins (int param1, int param2){
code code code
}
int executeCycle(string p1_name, string p2_name){
code code code
}
void stateWinner(string winner_name){
if(!winner_name.empty()){
code code code
}
I hope it's fine if the code above isn't accurate. I think the point is that once I add my if statement to the main function, the two errors show up.
actually...now that I look at it, they both seem like similar errors. I just don't know why they both appear...
Sorry if this is an obvious answer or if it isn't clear.
The "announceWinner" function is not defined anywhere, ie there's no
void announceWinner () {
// code
}
anywhere. Either you haven't written it yet, or the file that contains it is not being compiled & linked with the main program.

What could cause initialization order to corrupt the stack?

Question is in bold below :
This works fine:
void process_batch(
string_vector & v
)
{
training_entry te;
entry_vector sv;
assert(sv.size() == 0);
...
}
However, this causes the assert to fail :
void process_batch(
string_vector & v
)
{
entry_vector sv;
training_entry te;
assert(sv.size() == 0);
...
}
Now I know this issue isn't shrink wrapped, so I'll restrict my question to this: what conditions could cause such a problem ? Specifically: variable initialization getting damaged dependant on appearance order in the stack frame. There are no malloc's or free's in my code, and no unsafe functions like strcpy, memcpy etc... it's modern c++. Compilers used: gcc and clang.
For brevity here are the type's
struct line_string
{
boost::uint32_t line_no;
std::string line;
};
typedef std::vector<boost::uint32_t> line_vector;
typedef std::vector<line_vector> entry_vector;
typedef std::vector<line_string> string_vector;
struct training_body
{
boost::uint32_t url_id;
bool relevant;
};
struct training_entry
{
boost::uint32_t session_id;
boost::uint32_t region_id;
std::vector< training_body> urls;
};
p.s., I am in no way saying that there is a issue in the compiler, it's probably my code. But since I am templatizing some code I wrote a long time ago, the issue has me completely stumped, I don't know where to look to find the problem.
edit
followed nim's suggestion and went through the following loop
shrink wrap the code to what I have shown here, compile and test, no problem.
#if 0 #endif to shrink wrap the main program.
remove headers till it compiles in shrink wrapped form.
remove library links till compiles in shrink wrapped form.
Solution: removing link to protocol buffers gets rid of the problem
The C++ standard guarantees that the following assertion will succeed:
std::vector<anything> Default;
//in your case anything is line_vector and Default is sv
assert(Default.size() == 0);
So, either you're not telling the whole story or you have a broken STL implementation.
OR: You have undefined behavior in your code. The C++ standard gives no guarantees about the behavior of a program which has a construct leading to UB, even prior to reaching that construct.
The usual case for this when one of the created objects writes beyond
its end in the constructor. And the most frequent reason this happens
in code I've seen is that object files have been compiled with different
versions of the header; e.g. at some point in time, you added (or
removed) a data member of one of the classes, and didn't recompile all
of the files which use it.
What might cause the sort of problem you see is a user-defined type with a misbehaving constructor;
class BrokenType {
public:
int i;
BrokenType() { this[1].i = 9999; } // Bug!
};
void process_batch(
string_vector & v
)
{
training_entry te;
BrokenType b; // bug in BrokenType shows up as assert fail in std::vector
entry_vector sv;
assert(sv.size() < 100);
...
}
Do you have the right version of the Boost libaries suited for your platform? (64 bit/32 bit)? I'm asking since the entry_vector object seems to be have a couple of member variables of type boost::uint32_t. I'm not sure what could be the behaviour if your executable is built for one platform and the boost library loaded is of another platform.