I created a method which should change values in my shop object. Unfortunately the values are not changed.
edit: 18:13
I could create a new shop object and return it, but I thought it should work with passing the object by reference?
To make my question clearer: My only problem is, that the new values are not stored in the object. I did run the debugging and the values are all correctly calculated and as expected.
The problem is in the lines:
shop.get_stock().push_back(inventory_bonbon);
This line should push a new inventory item to the vector (containing the inventory items), if this inventory item is currently not in stock.
Here I increase the amount of an inventory item, when the item is currently in stock:
i_inventory_shop.increase_amount(shop.get_stock()[i], amount);
(I have unit-tested the increase_amount() method and it works fine.)
The two lines are called as expected (meaning I find when an item is in stock or not).
void IRooms::increase_inventory_shop(Shop & shop, Bonbon & bonbon, int amount)
{
OutputDebugString("I_Game Logic increase_inventory_shop called \n");
IInventoryItemsBonbons i_inventory_shop;
bool bonbon_in_shop = false;
for (int i = 0; i < shop.get_stock().size(); i++)
{
OutputDebugString(("I_Game Logic shop vector size \n" + std::to_string(shop.get_stock().size()) + "\n").c_str());
OutputDebugString(("I_Game Logic bonbon name \n" + bonbon.get_name() + "\n").c_str());
OutputDebugString(("I_Game Logic bonbon amount \n" + std::to_string(amount) + "\n").c_str());
if (bonbon.get_name() == shop.get_stock()[i].get_bonbon().get_name())
{
bonbon_in_shop = true;
OutputDebugString("Bonbon found \n");
i_inventory_shop.increase_amount(shop.get_stock()[i], amount);
break;
}
}
if (bonbon_in_shop == false) {
OutputDebugString("Bonbon not found \n");
InventoryItemBonbons inventory_bonbon = i_inventory_shop.create(amount, bonbon);
shop.get_stock().push_back(inventory_bonbon);
}
}
This method calls: (the method below, I have tested it)
void IInventoryItemsBonbons::increase_amount(InventoryItemBonbons & inventoryitem_shop, int amount)
{
int old_amount = inventoryitem_shop.get_amount();
int new_amount = old_amount + amount;
inventoryitem_shop.set_amount(new_amount);
}
edit 17:51:
Shop.h
std::vector<InventoryItemBonbons> get_stock();
Shop.ccp
std::vector<InventoryItemBonbons> Shop::get_stock()
{
return stock_bonbons;
}
_____________________________________________________________________________edit: 19:54
I have now introduced local variables and I return the local shop.
Shop IRooms::increase_inventory_shop(Shop & shop, Bonbon & bonbon, int amount)
{
Shop shop_temp = shop;
std::vector<InventoryItemBonbons> inventory_items_temp = shop.get_stock();
IInventoryItemsBonbons i_inventory_shop;
bool bonbon_in_shop = false;
for (int i = 0; i < shop_temp.get_stock().size(); i++)
{
if (bonbon.get_name() == shop_temp.get_stock()[i].get_bonbon().get_name())
{
bonbon_in_shop = true;
i_inventory_shop.increase_amount(inventory_items_temp[i], amount);
break;
}
}
if (bonbon_in_shop == false) {
InventoryItemBonbons inventory_bonbon = i_inventory_shop.create(amount, bonbon);
inventory_items_temp.push_back(inventory_bonbon);
}
shop_temp.set_stock(inventory_items_temp);
//shop = shop_temp;
//return shop;
return shop_temp;
}
The only thing I want to know, why the values of shop won't change. I have tried to copy shop_temp to shop, but even this does not work.
std::vector<InventoryItemBonbons> get_stock();
Since get_stock returns by value, not by reference, any changes to the value returned will be lost as soon as that temporary goes out of scope.
shop.get_stock().push_back(inventory_bonbon);
So this modifies the temporary returned by get_stock, which immediately goes out of scope, is destroyed, and the modification is lost.
You probably wanted:
std::vector<InventoryItemBonbons>& get_stock();
...
std::vector<InventoryItemBonbons>& Shop::get_stock()
{
return stock_bonbons;
}
Related
When returning a ship to the port, speed becomes 0.0 and user inputs shield and fuel.
–If fuel is 0.0, the ship gets destroyed
–Ships still in the priority_queue take 10 shield damage and lose 15 fuel
–If shield or fuel become less than 0.0, the ship gets destroyed
Trying to implement these instructions for my final project. The ships are pointer types and they are in a priority queue named 'battlefield'. The ships also exist in a list of pointers called 'port'. I'm trying to destroy the ships that receive lethal damage but when I try to show them, the Qt program crashes and I get bad_alloc error. This is the last thing I have to do for my project :(
Important code blocks from various files:
I already tried to delete the ships from the port, also tried directly deleting them from the port but the priority_queue gets messed up.
class Civilization {
string name;
int x;
int y;
list<Villager> villagers;
list<Ship*> port;
priority_queue<Ship*, vector<Ship*>, Ship::comp> battle;
}
void Civilization::damageShips()
{
priority_queue<Ship*, vector<Ship*>, Ship::comp> copy = battle;
Ship *s = battle.top();
s->setSpeed(0.0);
while(!copy.empty()) {
Ship *s = copy.top();
s->setShield(s->getShield() - 10);
s->setFuel(s->getFuel() - 15);
copy.pop();
}
priority_queue<Ship*, vector<Ship*>, Ship::comp> temp;
while(!copy.empty()) {
Ship *s = copy.top();
string id = s->getId();
if (s->getShield() > 0 && s->getFuel() > 0) {
temp.push(s);
} else
deleteShip(id);
copy.pop();
}
battle = temp;
battle.pop();
}
void battlefielddisplay::setCivilization(Civilization *civilizaition)
{
size_t size = civilizaition->battlefieldSize();
ui->battlefield_table->setRowCount(int(size));
Civilization &c = *civilizaition;
priority_queue<Ship*, vector<Ship*>, Ship::comp> copy = c.getBattlefield();
int cnt = 0;
while(!copy.empty()) {
Ship *s = copy.top();
QString id = QString::fromStdString(s->getId());
QString fuel = QString::number(s->getFuel());
QString speed = QString::number(s->getSpeed());
QString shield = QString::number(s->getShield());
QString warriors = QString::number(s->size());
QTableWidgetItem *idItem = new QTableWidgetItem(id);
QTableWidgetItem *fuelItem = new QTableWidgetItem(fuel);
QTableWidgetItem *speedItem = new QTableWidgetItem(speed);
QTableWidgetItem *shieldItem = new QTableWidgetItem(shield);
QTableWidgetItem *warriorsItem = new QTableWidgetItem(warriors);
ui->battlefield_table->setItem(cnt, 0, idItem);
ui->battlefield_table->setItem(cnt, 1, fuelItem);
ui->battlefield_table->setItem(cnt, 2, speedItem);
ui->battlefield_table->setItem(cnt, 3, shieldItem);
ui->battlefield_table->setItem(cnt, 4, warriorsItem);
cnt++;
copy.pop();
}
}
void MainWindow::on_battle_remove_ship_clicked()
{
if (flag) {
Civilization* c = videogame.searchCivilization(ui->civilization_search_input->text().toStdString());
double shield = ui->shield_battle_remove->value();
double fuel = ui->fuel_battle_remove->value();
Ship *s = c->getBattleShip();
s->setSpeed(0.0);
s->setShield(shield);
s->setFuel(fuel);
c->damageShips();
qDebug() << "[✔]" << "Removed ship from battlefield";
} else
QMessageBox::information(this, "Error", "Civilization not found");
}
bool Civilization::deleteShip(string &id)
{
bool found = false;
for(size_t i(0); i < shipSize(); ++i) {
auto it = port.begin();
advance(it, i);
auto x = *it;
if (x->getId() == id) {
port.erase(it);
delete x;
--i;
found = true;
}
}
return found;
}
The main problem I see is that you delete the objects without removing the pointers from the container. You are iterating the same container multiple times and trying to access the deleted objects.
An additional problem is that you have multiple copies of the same queue so even removing the pointer from the main container may cause problems.
Try to reconsider the algorithm paying special attention to the life time of the objects. For example you may have a lazy deletion: instead of deleting just mark the objects as those that shall be deleted later. You may have a cleanup at the end of your function.
So I'm working with Steamworks (leaderboards) and i have some strange issue. When i fire my function to get scores, from debugging i know that it works just fine.However my array after 1st function run always returns default values.After I fire function for the second time everything works perfectly fine. I tried to track down the issue however i failed.
Here is my whole code that i am using in this case:
Struct for stats
USTRUCT(BlueprintType)
struct FScorePackage
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Leaderboard")
FString PlayerName = "working";
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Leaderboard")
int32 Rank = 0;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Leaderboard")
int32 Score = 0;
};
Function that sent request to the steam:
.h
UFUNCTION(BlueprintCallable, Category = "Steam|Leaderboard", meta = (Latent, LatentInfo = "LatentInfo", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject"))
TArray<FScorePackage> DownloadScoresAroundUser(UObject* WorldContextObject, int AboveUser, int BelowUser, struct FLatentActionInfo LatentInfo);
.cpp
TArray<FScorePackage> USteamLeaderboard::DownloadScoresAroundUser(UObject* WorldContextObject, int AboveUser, int BelowUser, struct FLatentActionInfo LatentInfo)
{
if (!m_CurrentLeaderboard)
{
return Scores;
}
if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject))
{
FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
if (LatentActionManager.FindExistingAction<SteamLeaderboardLatentClass>(LatentInfo.CallbackTarget, LatentInfo.UUID) == NULL)
{
// load the specified leaderboard data around the current user
SteamAPICall_t hSteamAPICall = SteamUserStats()->DownloadLeaderboardEntries(m_CurrentLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -AboveUser, BelowUser);
m_callResultDownloadScore.Set(hSteamAPICall, this,&USteamLeaderboard::OnDownloadScore);
LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, new SteamLeaderboardLatentClassScores(LatentInfo));
return Scores;
}
return Scores;
}
return Scores;
}
Now callback function from steam:
.h
void OnDownloadScore(LeaderboardScoresDownloaded_t *pResult, bool bIOFailure);
CCallResult <USteamLeaderboard, LeaderboardScoresDownloaded_t> m_callResultDownloadScore;
.cpp
void USteamLeaderboard::OnDownloadScore(LeaderboardScoresDownloaded_t *pCallback, bool bIOFailure)
{
if (!bIOFailure)
{
m_nLeaderboardEntries = __min(pCallback->m_cEntryCount, 30);
for (int index = 0; index < m_nLeaderboardEntries; index++)
{
SteamUserStats()->GetDownloadedLeaderboardEntry(pCallback->m_hSteamLeaderboardEntries, index, &m_leaderboardEntries[index], NULL, 0);
}
TranslateEntries();
scores = true;
}
}
And finally function that write scores in Array:
.h
UFUNCTION(BlueprintCosmetic, Category = "Steam|Leaderboard")
TArray<FScorePackage> TranslateEntries();
.cpp
TArray<FScorePackage> USteamLeaderboard::TranslateEntries()
{
FScorePackage ThisScore;
Scores.Init(ThisScore, 30);
for (int i = 0; i < 30; i++)
{
ThisScore.PlayerName = GetSteamName(m_leaderboardEntries[i].m_steamIDUser);
ThisScore.Rank = m_leaderboardEntries[i].m_nGlobalRank;
ThisScore.Score = m_leaderboardEntries[i].m_nScore;
Arrayas[i] = ThisScore;
}
return Scores;
}
Scores array is just static TArray Scores and scores=true is only for latent check to go on with functions after calling DownloadScoresAroundUser :)
My normal flow with this is:
1.I already have handle for leaderboard.
2.I'm calling DownloadScoresAroundUser.
3.Flow goes to latent which cannot proceed becouse of scores=false.
4.After i got callback from steam OnDownloadScore fires, giving me all needed info(checked if really and it does!).
5.Then i call TranslateEntries to get all scores with names and rank in Array.
6.Then I'm printing whole array (with break package in unreal) and get default values of my struct.
7.After i fire whole cycle again i get proper values.
If any further info is required let me know :)
This is a bit of a guess, but it appears that you have a latency issue. When you make the request to download the scores, this is a time consuming call that does not block. You set up a callback that will be called when the scores are ready, then return the existing empty Scores object.
When you make your second call, enough time has passed for the scores to have download and Scores to be populated, so it returns some scores.
Note that you have a potential race condition, where DownloadScoresAroundUser can access (return) Scores while your callback is populating that vector.
Here's one possible solution. Before the scores have completed loading, DownloadScoresAroundUser returns an empty Score (or possibly one indicating that scores are being loaded). Once the scores have been loaded and Scores populated, it will return those. Also, the callback (besides populating Scores) can in some fashion notify the caller(s) of DownloadScoresAndUser that new scores are available. They can respond to that by calling in again to get the updated scores and refresh the display.
Translateentries copy data from 0 to 30 but only "Callback->m_cEntryCount" are actually initialized. So if it < at 30, the data from "Callback->m_cEntryCount" to 30 may be wrong. Can you print out the value of this variable "in SteamLeaderboard::OnDownloadScore" ?
How to correct return created std::list through function argument? Now, I try so:
bool DatabaseHandler::tags(std::list<Tag> *tags)
{
QString sql = "SELECT * FROM " + Tag::TABLE_NAME + ";";
QSqlQueryModel model;
model.setQuery(sql);
if(model.lastError().type() != QSqlError::NoError) {
log(sql);
tags = NULL;
return false;
}
const int count = model.rowCount();
if(count > 0)
tags = new std::list<Tag>(count);
else
tags = new std::list<Tag>();
//some code
return true;
}
After I can use it:
std::list<Tag> tags;
mDB->tags(&tags);
Now, I fix my function:
bool DatabaseHandler::tags(std::list<Tag> **tags)
{
QString sql = "SELECT * FROM " + Tag::TABLE_NAME + ";";
QSqlQueryModel model;
model.setQuery(sql);
if(model.lastError().type() != QSqlError::NoError) {
log(sql);
*tags = NULL;
return false;
}
const int count = model.rowCount();
if(count > 0)
*tags = new std::list<Tag>(count);
else
*tags = new std::list<Tag>();
for(int i = 0; i < count; ++i) {
auto record = model.record(i);
Tag tag(record.value(Table::KEY_ID).toInt());
(*tags)->push_back(tag);
}
return true;
}
It works but list return size 4 although loop executes only 2 iterations and empty child objects (if I just called their default constructor). The Tag class hasn't copy constructor.
Since you passed an already instantiated list as a pointer to the function, there is no need to create another list.
In that sense, you question is pretty unclear. I'd suggest you read up a bit on pointers, references and function calls in general.
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/functions/
UPDATE: I still strongly suggest you read up on the mentioned topics, since you don't know these fundamental points.
Anyway, this is what you probably want to do (event though I would suggest using references, here is the solution with pointers):
bool someFunc(std::list<Tag> **tags) {
// by default null the output argument
*tags = nullptr;
if (error) {
return false;
}
// dereference tags and assign it the address to a new instance of list<Tag>
*tags = new std::list<Tag>();
return true
}
std::list<Tag> *yourList;
if (someFunc(&yourList)) {
// then yourList is valid
} else {
// then you had an error and yourList == nullptr
}
However, this is not idiomatic C++. Please read a modern book or tutorial.
Use a reference.
bool DatabaseHandler::tags(std::list<Tag>& tags);
std::list<Tag> tags;
mDB->tags(tags);
You'll have to change all the -> to ., of course. Every operation done on the reference in the function will be done to the original tags list it was called with.
EDIT: If you want to create the list inside the function and return it, you have a couple options. The closest, I think, is to just return a list pointer, and return nullptr if the function fails.
//beware, pseudocode ahead
std::list<Tag>* DatabaseHandler::tags() //return new list
{
if (success)
return new std::list<Tag>(...); //construct with whatever
else
return nullptr; //null pointer return, didn't work
}
std::list<Tag> tags* = mDB->tags();
You could alternatively have it return an empty list instead, depending on how you want it to work. Taking a reference to a pointer would work the same way, too.
bool DatabaseHandler::tags(std::list<Tag>*&); //return true/false
std::list<Tag>* tags;
mDB->tags(tags); //tags will be set to point to a list if it worked
enum { WOOD, BRICK, GRAIN, HEMP, WOOL, RAWMETAL, HONEY, SALT, METALGOODS, MEAD, CLOTH, BEER, STOCKFISH, CLOTHING, CHEESE, PITCH, PELTS, MEAT, WINE, SPICES, TOTALRESOURCES };
// An array of strings for each of the resource names
// As long as these are in the same order as the enum everything should match up
// .: resName[PIGIRON] is "Pig Iron"
string resName[]{ "Wood", "Brick", "Grain", "Hemp", "Wool", "Raw Metal", "Honey", "Salt", "Metal Goods", "Mead", "Cloth", "Beer", "Stockfish", "Clothing", "Cheese", "Pitch", "Pelts", "Meat", "Wine", "Spices" };
enum { Edinburgh, Scarborough, Boston, London, Bruges, Haarlem, Nimwegen, Groningen, Cologne, Minden, Bremen, Erfurt, Hamburg, Lubeck, Rostock, Berlin, Ripen, Flensburg, Aalborg, Naevsted, Bergen, Stavanger, Oslo, Stockholm, Gothenburg, Malmo, Ahus, Visby, Stettin, Posen, Breslau, Danzig, Thorn, Warsaw, Konigsberg, Kaunas, Riga, Reval, Helsinki, Novgorod, TOTALTOWNS};
string townName[]{ "Edinburgh", "Scarborough", "Boston", "London", "Bruges", "Haarlem", "Nimwegen", "Groningen", "Cologne", "Minden", "Bremen", "Erfurt", "Hamburg", "Lubeck", "Rostock", "Berlin", "Ripen", "Flensburg", "Aalborg", "Naevsted", "Bergen", "Stavanger", "Oslo", "Stockholm", "Gothenburg", "Malmo", "Ahus", "Visby", "Stettin", "Posen", "Breslau", "Danzig", "Thorn", "Warsaw", "Konigsberg", "Kaunas", "Riga", "Reval", "Helsinki", "Novgorod"};
class resource
{
public:
float demand, production, businessNeeds, businessProduction;
// This function, called a constructor, is run every time a new resource is created
// In this case, it assigns 0 to everything
resource()
{
demand = 0;
production = 0;
businessNeeds = 0;
businessProduction = 0;
}
float net()
{
return (this->production - this->demand);
}
float businessNet()
{
return (this->businessProduction - this->businessNeeds);
}
};
class town
{
public:
// The array of pointers to each of a our resource objects
resource *resList[TOTALRESOURCES];
// This is the town constructor
town()
{
// Loops through the array and creates a new resource object in each
// the resource constructor assigns the default values of 0.
for (int i = 0; i < TOTALRESOURCES; i = i + 1)
{
resList[i] = new resource();
}
}
~town()
{
// Loops through the array and deletes each resource object
for (int i = 0; i < TOTALRESOURCES; i = i + 1)
{
delete resList[i];
}
};
int main()
{
//What do I do here?
for (int i = 0; i < TOTALTOWNS; i++)
{
town townName[i];
}
system("pause");
return 0;
}
So, I'm a software engineering student and I just switched majors so I decided to take some personal time to learn how to code in c++ a bit better. I decided to build a program that can plan the logistics for a videogame called Patrician IV.
I have put about 5 days worth of work into this project and have found some serious problems with my initial code (hard to add new functionality and change stuff around). So I took a step back and am trying to build my classes in a more succinct manner while also being able to loop through each instance of town later in a loop so I can update the demand, production, businessNeeds, and businessProduction values easily. I was copying and pasting about 6 lines of code 40 times before this.
I want to know:
(A) is it possible to do what I want - i.e. can I use enums and a for-loop to construct instances of town.
(B) how to loop through each of the towns so that I can add values to the resource variables.
(C) a third-grade-level explanation of how to use pointers for similar purposes would also be great.
:) THANK YOU!
In your main function, use the same idea as resList to initialize your town objects, so:
town* townName[TOTALTOWNS]
for (int i = 0; i < TOTALTOWNS; i++)
{
townName[i]= new town();
}
Then, I'm guessing you want to give different values for each of the different resources. Switch statements go along with enums well. So I would recommend something like this:
for (int i = 0; i < TOTALRESOURCES; i = i + 1)
{
switch(i)
{
case WOOD:
townName[EDINBURGH]->resList[WOOD]->demand= yourValue;
break;
case BRICK:
break;
}
}
Or if you're cycling through towns:
for (int i = 0; i < TOTALTOWNS; i = i + 1)
{
switch(i)
{
case EDINBURGH:
break; //etc.
}
}
If you only want to update a single town or resource, depending on how you're organizing everything, you could create something like this. A function that takes your town array and the enum indexes, like this:
updateTownResources(town* (*townName)[TOTALTOWNS], int townEnum, int resourceEnum, int dValue, int pValue )
{
townName[townEnum]->resList[resourceEnum]->demand= dValue;
townName[townEnum]->resList[resourceEnum]->production= pValue;
//etc...
}
int main()
{
std::vector<town*> townArray;
//What do I do here?
for (int i = 0; i < TOTALTOWNS; i++)
{
town* pTown = new(std::nothrow) town;
townArray.push_back (pTown);
}
std::vector<town*>::iterator iter = townArray.begin();
for (;iter != townArray.end(); iter++) {
(*iter); // gives access to individual objects
}
system("pause");
return 0;
}
I have a memory issue with a class of mine. The issue occurs when I create an object in a member function of a class. It is about the class below. I removed the member functions because they aren’t necessary:
class User
{
private:
bool locked;
bool active;
std::vector<City> * userCitys;
UserData userData;
Credentials credentials;
The problem occurs when I call this function:
int User::addCity(CityData cityData)
{
lockUserObject(); //Everything is fine here
City cityToAdd; //When this object is created, the memory of userCitys will get overridden
cityToAdd.activate();
userCitys->push_back(cityToAdd);
int cityID = userCitys->size() - 1;
userCitys->at(cityID).editCityData(cityData);
unlockUserObject();
return cityID;
}
In the first place I created userCitys on the stack. For test purpose I placed it on the Heap. The address of userCitys get overridden by some data. I can’t find the problem. the City is just a basic class:
Part of the header:
class City
{
private:
bool active;
Supplies supplies;
std::vector<Building> buildings;
std::vector<Company> companies;
std::vector<Share> shares;
std::vector<Troop> troops;
CityData cityData;
Constructor:
City::City()
{
active = false;
}
How is it possible that userCitys get overridden? This all happens on a single Thread so that can’t be a problem. I tried a lot of thing, but I can’t get it to work. What is the best approach to find the problem?
Edit:
Lock function:
void User::lockUserObject()
{
for( int i = 0; locked ; i++)
{
crossSleep(Settings::userLockSleepInterval);
if( i >= Settings::userLockMaxTimes )
Error::addError("User lock is over userLockMaxTimes",2);
}
locked = true;
}
I call the code here (Test function):
City * addCity(User * user)
{
Location location;
location.x = 0;
location.y = 1;
CityData citydata;
citydata.location = location;
citydata.villagers = 0;
citydata.cityName = "test city";
int cityID = user->addCity(citydata); //addCity is called here
City * city = user->cityAction(cityID);;
if( city == NULL)
Error::addError("Could not create a city",2);
return city;
}
The add user (Test code):
User * addUser()
{
UserData test;
test.name = "testtest";
Credentials testc("testtest",3);
//Create object user
int userID = UserControle::addUser(test,testc);
User * user = UserControle::UserAction(userID);
if( user == NULL)
Error::addError("Could not create a user",2);
return user;
}
My test function:
void testCode()
{
User * user = addUser();
City * city = addCity(user);
}
This function in called in main:
int main()
{
testCode();
return 0;
}
Here are UserAction and addUser in UserControle:
int UserControle::addUser(UserData userdata, Credentials credentials)
{
int insertID = -1;
for( int i = 0; i < (int)UserControle::users.size(); i++)
{
if( !UserControle::users.at(i).isActive() )
{
insertID = i;
break;
}
}
User userToInsert(userdata,credentials);
if( insertID != -1 )
{
UserControle::users.insert( UserControle::users.begin() + insertID,userToInsert);
return insertID;
}
else
{
UserControle::users.push_back(userToInsert);
return UserControle::users.size() - 1;
}
}
User* UserControle::UserAction(int userID) //check all indexes if greater then 0!
{
if( (int)UserControle::users.size() <= userID )
{
Error::addError("UserAction is out of range",3);
return NULL;
}
if( !UserControle::users.at(userID).isActive())
{
Error::addError("UserAction, the user is not active.",3);
return NULL;
}
return &UserControle::users[userID];
}
There's a few things you could try:
Remove code until the fault goes away. In other words, distill a minimal example from your code. I guess you'll then see the error yourself, otherwise post that small example program here and others will.
Don't use raw pointers. The question with those is always who owns what they point to. Use smart pointers instead, e.g. unique_ptr (C++11) or auto_ptr (C++98) for exclusive ownership.
If you have pointer members like "userCities", you need to think about what happens when copying instances of that class (you already wrote a proper destructor, or?). So, either prevent copying (make copy-constructor and assignment operator private and without implementing it) or implement them in a way that the vectors are properly cloned and not shared between different instances.
Don't use C-style casts. If those are necessary to get anything through the compiler, the code is probably broken.