Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

struct simple question 1

Status
Not open for further replies.

svar

Programmer
Aug 12, 2001
349
GR
I'm wondering ifd there is a standard "best way" to
-check if a particular member of a struct exists
-delete a particular member of a struct

Thanks, svar
 
What do you mean "exists"
Code:
struct foo {
    int bar;
};

At run-time, bar always exists, and it cannot be deleted.

--
 
Sorry, bad way to put it
Actually I have a bunch of records(array of structs)
e.g. say

struct foo {
int bar;
} objectnames[]={1,2,5,7,15};


What I really want is to
check if a value of 7 exists(it does) and if so delete it
and if a value of 8 exists(it does not)

Does this make more sense now?

 
> check if a value exists
Well the simple way is to use a for loop to examine each element of the array, and decide if that is the one you're looking for.
If your array is sorted in some way, then you can use the bsearch() function for greater efficiency.

> if so delete it
You can't actually delete something from an array (in the sence that the array will now take up less memory).
Something quick would be to have a 'validity' flag in the structure, so deleting an element would be
[tt]array[element].deleted = 1;[/tt]

If you don't want these kinds of holes in your array, then you have to move the array about a bit, say

[tt]array[element] = array[last--];[/tt]
Quick, but destroys the sort order if you're using bsearch()

[tt]for(i=element;i<last-1;i++)
array = array[i+1];
last--;[/tt]
Slower, but preserves the sort order for bsearch()

--
 
Thanks, the actual problem is
to optimize some function of NxN attributes, e.g. there is
a 'cost' function A[j]
and one loops recursively over all i and j and all
combinations are covered such that no i or j is repeated
in the combination(i.e. if we have people and jobs assigned to them each job gets assigned to one person and vice versa)
If you look for instance in Perl, you just test whether
a hash key exists to see if this i has been used before
in the combination. Ultimately this boils down to
checking the array values, so one might keep an order
in the array to search it more eficiently

Thanks, svar
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top