Set pointer to element in vector to null, then check whether pointer is null (C++) - c++

I would like to set pointers to some elements in my vector array to NULL (based on a criteria), and then check whether an element pointer is NULL. If the pointer pointing that element is NULL, I remove the element from my vector array.
My compiler is giving me an error, saying that the address expression must be an lvalue or function designator and I do not understand why (line location commented in code). Since I am taking the address of the value using &, am I not seeing if the pointer pointing to that element is NULL?
I included the preceding code as the error may lie there,
Relevant code:
vector<particle> pl = c.particlelist;
vector<particle> noncollision = c.particlelist;
vector<vector<particle>> collisionlist = new vector<vector<particle>>();
for (int i = 0; i < c.numparticles-1; i++){
particle first = pl[i];
for (int j = i+1; j < c.numparticles; j++)
{
particle second = pl[j];
double d = distance(first, second);
if (d==0)
{
vector<particle> temp = {pl[i], pl[j]};
collisionlist.push_back(temp);
noncollision[i].setxposint(NULL);
noncollision[j].setxposint(NULL);
}
else
{
}
}
}
int j = 0;
for (int i = 0; i < noncollision.size(); i++)
{
if (&(noncollision[i].getxpos()) == NULL) ////// ERROR HERE
{
noncollision.erase(noncollision.begin()+i);
}
else
{
j++;
}
}
I am new to C++, and if you could suggest a more elegant way to do this, or a fix, it would be much appreciated. I also assume that my method of setting the pointer to an element, noncollision[i].setxposint(NULL); is correct? Can I return an integer using a function, and take the address?
Functions for getxpos and setxposint:
int particle::getxpos(){
return xpos;
}
void particle::setxposint(int b){
xpos = b;
}

You're using & to take a pointer to a temporary vale (the return from getxpos) which isn't allowed; since a temporary will be going away, the address won't be useful in any way so the language doesn't allow it. It certainly wouldn't ever be NULL even if you could get its address.

noncollision[i].setxposint(NULL);
All that line is doing is setting xpos to zero. Generally the term NULL is used with pointers, and 0 is used with things like integers. NULL is usually a macro for 0L anyway.
&(noncollision[i].getxpos()) == NULL
What this is doing, which is incorrect, is attempting to take the address of the return value from the member method getxpos() and compare it to NULL. Whereas what you really want to do is simply see if the function returns zero. So simply change this line to:
noncollision[i].getxpos() == 0

I'll explain why the compiler doesn't understand what you mean.
When you write
&(someFunction())
you are asking for the address of the thing that the function returns. But functions return values. A value doesn't have an address. Variables have addresses.
When something is a word of memory (which will contain a value), it can be used as an lvalue (left-value), because you can put things into that word of memory:
int b = 1; //make room for an `int` on the stack, then put a `1` there.
When something is just a value, it can only ever be used as an rvalue. The following would not compile, for the same reason that your code would not:
int b; //make room for an `int` on the stack.
42 = b; //ERROR, this makes no sense.
if (42 == NULL) { std::cout << "this is never true" << std::endl; }
&42; //ERROR, 42 isn't a piece of memory, it's a value.
(Caveat: you can use values to refer to words in memory: this usage is called a pointer, e.g.
int b = 1;
*((int *)(42)) = b;
meaning "put the value of b into the memory which has the address 42. This compiles fine (but crashes if you're not allowed to write to the memory at 42.)

It looks to me you're trying to keep track of 'visited' items, not sure exactly in which way.
Instead of "modifying" the items, you could use an "external" mark. A set looks to be fine here. You could use a set of iterators into the particle list, or in this case a set of indices (i,j) which will likely be more stable.
Here's a start:
#include <vector>
#include <set>
struct particle { };
double distance(particle const&, particle const&) { return 1.0; }
struct context
{
std::size_t numparticles;
std::vector<particle> particlelist;
context() : numparticles(100), particlelist(numparticles) {}
};
static context c;
int main()
{
using std::vector;
using std::size_t;
vector<particle> pl = c.particlelist;
vector<vector<particle>> collisionlist;
std::set<size_t> collision;
for(size_t i = 0; i < c.numparticles-1; i++)
{
particle first = pl[i];
for(size_t j = i+1; j < c.numparticles; j++)
{
particle second = pl[j];
double d = distance(first, second);
if(d < 0.0001)
{
collisionlist.push_back({pl[i], pl[j]});
collision.insert(i);
collision.insert(j);
}
else
{
}
}
}
for(size_t i = 0; i < pl.size(); i++)
{
if(collision.end() != collision.find(i))
{
// do something
}
}
// alternatively
for (int index : collision)
{
particle& p = pl[index];
// do something
}
}
NOTE Be very very wary of floating point comparison like
if (d==0.0) // uhoh
because it will likely not do what you expect
How dangerous is it to compare floating point values?
What is the most effective way for float and double comparison?
Is floating-point == ever OK?

It seems that you are trying to check pairs of points for collisions. You then record for each point whether it has any collision. This is best handled by a simple list of flags:
std::vector<bool> has_collision(c.numparticles, false); // init: no collisions found
Afterwards:
if (d==0)
{
has_collision[i] = true;
has_collision[j] = true;
}
At the end, iterate over the list of flags and get the points that have no collisions:
for (size_t i = 0; i < c.numparticles; ++i)
{
if (!has_collision[i])
{
// whatever
// possibly push_back pl[i] into some list
}
}
In addition: using a vector to hold a pair (i,j) of points is confusing. Standard library has the std::pair type for purposes such as this.
Also: you don't need explicit dynamic allocation (new); let Standard Library manage memory for you in a safe, non-confusing way. Instead of
vector<vector<particle>> collisionlist = *new vector<vector<particle>>();
Use
vector<vector<particle>> collisionlist;
(or vector<pair<particle, particle>>, as described above).

Related

C++ There is a bool return type function returning (24) here

First of all sorry for too much code
Here there is a vector (teamNum) with type class, the class contain a vector (player) with type struct, it is a little complicated, but here in this function I need to check if there is a player in teamNum which contain tName equal to _tname (function parameter) contain (the player) pID equal to _pID (function parameter)
bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
if (teamNum[i].tName == _tname)
{
for (int j = 0; j < teamNum[i].player.size(); j++)
{
if (teamNum[i].player[j].pID == _pID)
return true;
}
}
else if (i == (teamNum.size() - 1))
{
return false;
}
}
}
And in the main
int main()
{
cout << "\n" << thereIsSimilarID("Leverpool", 1) << endl;
}
The output is 24 !!!!!
(good note that this happen just when the team (Leverpool) is the last team in the vector teamNum)
Again sorry for too much code but I need to know the bug not only fix the problem I need to learn from you
You encountered undefined behaviour.
If you take the if (teamNum[i].tName == _tname)-branch on the last element, but find no player with the correct pID, you don't return anything. Which means, that the return value is whatever random value is currently in the memory location that should hold the return value. In your case it happens to 24. But theoretically, everything could happen.
The same problem occurs when teamNum is empty.
The solution is to make sure to always return a value from a function (except if it has return type void of course):
bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
// In this loop return true if you find a matching element
}
// If no matching element was found we reach this point and make sure to return a value
return false;
}
You should take a look at your compiler settings and enable all the warnings. And often it's good to let it treat certain warnings as errors.

std::unordered_map how to free struct created with malloc. Are 2 queries into the map required?

The following block of code seems to run fine
Generates:
Add 1000 things
_MyMap now holds [1000] things
_MyMap free'd and erased. size now [0]
#include <unordered_map>
#include <iostream>
typedef struct _entry
{
int now;
} ENTRY, * PENTRY;
std::unordered_map<int, PENTRY> _MyMap;
typedef std::unordered_map<int, PENTRY>::iterator itEntry;
int Now()
{
return 10;
}
main function, adding comments because the site won't let me just add code
int main()
{
PENTRY pE = NULL;
std::pair<itEntry, bool> r;
printf("Add 1000 things\n");
for (int i = 0; i < 1000; i++)
{
pE = (PENTRY)malloc(sizeof(ENTRY));
pE->now = Now();
r = _MyMap.insert(std::make_pair(i, pE));
if (false == r.second)
{
printf("For some crazy reason its already there\n");
continue;
}
}
// OK, theres probably 1000 things in there now
printf("_MyMap now holds [%u] things\n", _MyMap.size() );
// The following seems stupid, but I don't understand how to free the memory otherwise
for (int i = 0; i < 1000; i++)
{
// first query
auto it = _MyMap.find(i);
// if malloc failed on an attempt earlier this could be NULL right?
// I've had free impls crash when given NULL, so I check.
if (it != _MyMap.end() &&
NULL != it->second)
free(it->second);
// second query
_MyMap.erase(i);
}
printf("_MyMap free'd and erased. size now [%u]\n", _MyMap.size());
return 0;
}
Questions are inline in the comments
You probably want this:
auto it = _Map.find(idUser);
if (it != _Map.end())
{
free(it->second);
_Map.erase (it);
}
But it's really not a good idea to store a raw pointer in a collection this way. You should, ideally, just store the data directly in the map rather than storing a pointer to it. Otherwise, use std::unique_ptr so that the destruction of the pointer automatically frees the data.

Returning a string * type array from a function back into the main

I'm new to C++ and I am working on a function to shuffle strings
It takes an array of strings, shuffles them, and returns them back to the main.
I am returning a pointer to an array of strings called shuffled. The problem I have is that when I try to save that new pointer to the array to another pointer in the main, I start getting weird values that either reference to a file location in my computer or a bunch of numbers.
I'll post the entire code here but really what you want to look at is the return types, how I return it and how I save it in main. Please tell me why my pointer is not referencing the working array that is created in the function. Here's the code:
#include <cstdio>
#include <string>
#include <ctime>
#include <new>
#include <cstdlib>
using namespace std;
const char * getString(const char * theStrings[], unsigned int stringNum)
{
return theStrings[stringNum];
}
string * shuffleStrings(string theStrings[])
{
int sz = 0;
while(!theStrings[sz].empty())
{
sz++;
}
sz--;
int randList[sz];
for(int p = 0; p < sz; p++)
{
randList[p] = sz;
}
srand(time(0));//seed randomizer to current time in seconds
bool ordered = true;
while(ordered)
{
int countNumberInRandList = 0;//avoid having a sz-1 member list length (weird error I was getting)
for(int i = 0; i < sz; i++)
{
int count = 0;
int randNum = rand()%(sz+1);//get random mod-based on size
for(int u = 0; u < sz; u++)
{
if(randList[u] != randNum)
{
count++;
}
}
if(count == sz)
{
randList[i] = randNum;
countNumberInRandList++;
}
else
i--;
}
//check to see if order is same
int count2 = 0;
for(int p = 0; p < sz; p++)
{
if(randList[p] == p)
{
count2++;
}
}
if(count2 < sz-(sz/2) && countNumberInRandList == sz)
{
ordered = false;
}
}
string * shuffled[sz];
for(int r = 0; r < sz; r++) //getting random num, and str list pointer from passed in stringlist and setting that value at shuffled [ random ].
{
int randVal = randList[r];
string * strListPointer = &theStrings[r];
shuffled[randVal] = strListPointer;
}
for(int i = 0; i < sz; i++)
{
printf("element %d is %s\n", i, shuffled[i]->c_str());//correct values in a random order.
}
return *shuffled;
}
int main()
{
string theSt[] = {"a", "b", "pocahontas","cashee","rawr", "okc", "mexican", "alfredo"};
string * shuff = shuffleStrings(theSt);//if looped, you will get wrong values
return 0;
}
Strings allocate their own memory, no need to give them the "length" like you would have to do for char arrays. There are several issues with your code - without going into the details, here are a few working/non-working examples that will hopefully help you:
using std::string;
// Returns a string by value
string s1() {
return "hello"; // This implicitly creates a std::string
}
// Also returns a string by value
string s2() {
string s = "how are you";
return s;
}
// Returns a pointer to a string - the caller is responsible for deleting
string* s3() {
string* s = new string;
*s = "this is a string";
return s;
}
// Does not work - do not use!
string* this_does_not_work() {
string s = "i am another string";
// Here we are returning a pointer to a locally allocated string.
// The string will be destroyed when this function returns, and the
// pointer will point at some random memory, not a string!
// Do not do this!
return &s;
}
int main() {
string v1 = s1();
// ...do things with v1...
string v2 = s2();
// ...do things with v2...
string* v3 = s3();
// ...do things with v3...
// We now own v3 and have to deallocate it!
delete v3;
}
There are a bunch of things wrong here -- don't panic, this is what happens to most people when they are first wrapping their brains around pointers and arrays in C and C++. But it means it's hard to put a finger on a single error and say "this is it". So I'll point out a few things.
(But advance warning: You ask about the pointer being returned to main, your code does indeed do something wrong with that, and I am about to say a bunch of things about what's wrong and how to do better. But that is not actually responsible for the errors you're seeing.)
So, in shuffleStrings you're making an array of pointers-to-string (string * shuffled[]). You're asking shuffleStrings to return a single pointer-to-string (string *). Can you see that these don't match?
In C and C++, you can't actually pass arrays around and return them from functions. The behaviour you get when you try tends to be confusing to newcomers. You'll need to understand it at some point, but for now I'll just say: you shouldn't actually be making shuffleStrings try to return an array.
There are two better approaches. The first is to use not an array but a vector, a container type that exists in C++ but not in C. You can pass arrays around by value, and they will get copied as required. If you made shuffleStrings return a vector<string*> (and made the other necessary changes in shuffleStrings and main to use vectors instead of arrays), that could work.
vector<string *> shuffleStrings(...) {
// ... (set things up) ...
vector<string *> shuffled(sz);
// ... (fill shuffled appropriately) ...
return shuffled;
}
But that is liable to be inefficient, because your program is then having to copy a load of stuff around. (It mightn't be so bad in this case, because a smallish array of pointers isn't very large and because C++ compilers are sometimes able to figure out what you're doing in cases like this and avoid the copying; the details aren't important right now.)
The other approach is to make the array not in shuffleStrings but in main; to pass a pointer to that array (or to its first element, which turns out to be kinda equivalent) into shuffleStrings; and to make shuffleStrings then modify the contents of the array.
void shuffleStrings(string * shuffled[], ...) {
// ... (set things up) ...
// ... (fill shuffled appropriately) ...
}
int main(...) {
// ...
string * shuffled[sz];
shuffleStrings(shuffled, theSt);
// output strings (main is probably a neater place for this
// than shuffleStrings)
}
Having said all this, the problems that are causing your symptoms lie elsewhere, inside shuffleStrings -- after all, main in your code never actually uses the pointer it gets back from shuffleStrings.
So what's actually wrong? I haven't figured out exactly what your shuffling code is trying to do, but that is where I bet the problem lies. You are making this array of pointers-to-string, and then you are filling in some of its elements -- the ones corresponding to numbers in randList. But if the numbers in randList don't cover the full range of valid indices in shuffled, you will leave some of those pointers uninitialized, and they might point absolutely anywhere, and then asking for their c_strs could give you all kinds of nonsense. I expect that's where the problem lies.
Your problem has nothing to do with any of the stuff you are saying. As you are a beginner I would suggest not presuming that your code is correct. Instead I would suggest removing parts that are not believed to be problematic until you have nothing left but the problem.
If you do this, you should quickly discover that you are writing to invalid memory.
part two : you can't seem to decide on the type of what you are returning. Are you building a pointer to an array to return or are you returning an array of pointers.... you seem to switch between these intermittently.
part three : read #Gareth's answer, he explains about passing parameters around nicely for your instance.

return pointers from function. Value not updated for one pointer

I have tried to obtain 2 pointers from a function and print it in main. the vague thing is one pointer seems to have recovered its values, while the other hasn't. And both the pointers, have the correct value inside the calling function, just before returning as well. Please tell me if you can identify any programmatic error that is preventing me from getting the right answer.
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
double* readctrls()
{
fstream inputs;
inputs.open("input_coods.txt");
int nol = 0,i = 0;
string line,temp,subtemptrans,subtemprots;
while(getline(inputs,line))
{
++nol;
}
// cout<<nol<<endl;
inputs.close();
inputs.open("input_coods.txt");
string *lines = new (nothrow) string[nol];
double* trans = new double[nol];
double* rots = new double[nol];
trans[0] =float(nol);
for(int i = 0; i<nol ; i++)
{
getline(inputs,lines[i]);
// cout<<lines[i]<<endl;
temp = lines[i];
// cout<<temp<<endl;
for(int j = 0; j<temp.length() ; j++)
{
if(temp.at(j) == ' ')
{
subtemptrans = temp.substr(0,j);
subtemprots = temp.substr(j+1,temp.length()-j);
// cout<<subtemprots<<endl;
*(trans+i+1) = ::atof(subtemptrans.c_str());
*(rots+i) = float(atoi(subtemprots.c_str()));
// cout<<rots[i]<<endl;
}
}
}
inputs.close();
// cout<<rots[2]<<endl;
return(rots,trans);
}
int main()
{
double *trans,*rots;
(rots,trans) = readctrls();
// cout<<sizeof(trans)<<endl;
for(int i=0;i<trans[0];i++)
{
cout<<*(trans+i)<<endl;
cout<<*(rots+i)<<endl;
}
}
The value of Trans is written fine in the memory and is perfectly retained from the main(). But the rots is giving garbage values of the order (e^-42). Please help me here.
C++ is neither Python nor Lua.
You can't return multiple values from a function.
return rots, trans;
This is the comma operator - evaluates its operands and yields the last (rightmost) one.
(rots, trans) = readctrls();
Likewise, this assigns to trans only, rots will be uninitialized.
Solution: you can either return a struct containing the two pointers, or pass them by reference, or whatever...
struct Foo {
double *rots;
double *trans;
};
Foo readctrls()
{
// ...
Foo r;
r.rots = rots;
r.trans = trans;
return r;
}
or:
void readctrls(double *&r, double *&t)
{
// ...
r = rots;
t = trans;
}
Other remarks:
Don't use raw arrays. std::vector<T> is generally preferred over T * in C++.
It's super wasteful to read the entire file just in order to count the lines, then read it once again to actually parse its contents. If you used an std::vector<double>, you could just vector.push_back(some_double); as you go along the lines, so you wouldn't have to walk through the file twice (you know, I/O is expensive, especially if the file is large).
You never delete the pointers that you allocate using new - here your program leaks memory.

Delete a record in an array

int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++ )
if (List[i].PersonID == Input) {
}
I am trying to make a function that deletes a record from the array based on the id input provided. I am not sure what to do beyond this here. Will I also need to shift the values in the array after a record is removed?
I can't tell what type your List is.
But you should go for something like this:
List.RemoveAt(i--);
List.DeleteAt(i--);
i-- will decrement i AFTER the function has been called.
You should not need to shift any values in the array if you are using the standard containers.
If you are responsible for the array, then you do need to shift your values.
** EDIT
Here is a link to an introduction to the standard containers. If you are managing your own dynamic array you should consider using these instead.
Here I'm assuming List is a primitive array of ints.
#include<algorithm> // where std::remove() resides
#include<iterator> // where std::distance() resides (not strictly necessary)
struct BadPerson {
BadPerson(int Bad) : Bad_(Bad) { }
bool operator()(const Element& Elem) const {
return Elem.PersonID == Bad_;
}
};
// ...
int *NewEnd = std::remove_if(List, List + ListLength, BadPerson);
// the list now has a new end, because elements were "removed".
// but they weren't really removed; the array still has the same fixed size.
int ListLength = std::distance(List, NewEnd);
I think the best way to remove elements from an array/vector is to use a copy approach with something like:
int write_ptr = 0;
for (int read_ptr=0; read_ptr < n; read_ptr++)
{
if (... keep element array[write_ptr] ? ...)
{
if (read_ptr != write_ptr)
array[write_ptr] = array[read_ptr];
write_ptr++;
}
}
// The new size of the array is write_ptr
This will allow to remove even multiple elements with just one pass.
The standard library includes this approach as std::remove_if, however until C++0X arrives it's annoying to use because of limitations of the language (the code needed to be able to specify the test becomes easily quite ugly).
int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++ )
{
if (List[i].PersonID == Input)
{
for(int j=i;j<size-1;j++)
{
List[j]=List[j+1];
}
}
}