Menu
  • HOME
  • TAGS

Mutable structs in a vector

Tag: vector,struct,rust

I'm trying to create a vector to keep track of enemies in a game that will hold a bunch of mutable structs. I have a world struct that has the enemies as a member of it as follows:

pub struct World {
  pub player      : Creature,
  pub enemies     : Vec<Creature>,
}

I create the enemies vector as follows:

 let mut enemies = vec![];
 let mut enemy = Creature::new(5, 5, map_start_x+5, map_start_y+5, "$", 10, 1, "")
 enemies.push(enemy);

later on in the code when I pull out an individual enemy from enemies for attacking and try to update the hp as follows:

  for enemy in self.enemies.iter() {
    if new_x == enemy.x && new_y == enemy.y {
      enemy.hp -= self.player.damage;
      return;
    }
  }

which is where the problem occurs since enemy is apparently not mutable at this point

 error: cannot assign to immutable field `enemy.hp`

Best How To :

Updated for the latest Rust version

Mutability in Rust is not associated with data structures, it is a property of a place (read: a variable) where the data is stored. That is, if you place a value in a mutable slot:

let mut world = World::new();

then you can take mutable references to this variable, and hence call methods which can mutate it.

Your structure owns all data it contains, so you can make it mutable any time you need. self.enemies.iter() returns an iterator which generates items of type &Creature - immutable references, so you can't use them to mutate the structure. However, there is another method on a vector, called iter_mut(). This method returns an iterator which produces &mut Creature - mutable references, which do allow changing data they point to.

for enemy in self.enemies.iter_mut() {
  if new_x == enemy.x && new_y == enemy.y {
    enemy.hp -= self.player.damage;
    return;
  }
}

// The following also works (due to IntoIter conversion)
for enemy in &mut self.enemies {
  if new_x == enemy.x && new_y == enemy.y {
    enemy.hp -= self.player.damage;
    return;
  }
}

Note that in order for this to work, you have to pass self by mutable reference too, otherwise it will be impossible to mutate anything under it, implying that you won't be able to obtain mutable references to internals of the structure, including items of the vector. In short, make sure that whatever method contains this loop is defined like this:

fn attack(&mut self, ...) { ... }

goroutine channels over a for loop

json,struct,go,channels

You're printing the channels info, not the data it contains. You don't want a loop, you just want to receive then print. json := <-index json.NewEncoder(os.Stdout).Encode(json) Now I do I need to point out, that code is not going to block. If you want to keep reading until all work...

C language, vector of struct, miss something?

c,vector,struct

What is happening is that tPeca pecaJogo[tam]; is a local variable, and as such the whole array is allocated in the stack frame of the function, which means that it will be deallocated along with the stack frame where the function it self is loaded. The reason it's working is...

R: recursive function to give groups of consecutive numbers

r,if-statement,recursion,vector,integer

Your sapply call is applying fun across all values of x, when you really want it to be applying across all values of i. To get the sapply to do what I assume you want to do, you can do the following: sapply(X = 1:length(x), FUN = fun, x =...

Golang - structs, intializing and memcpy - what is the proper way?

arrays,struct,go,initialization,custom-type

So basically given these basic types: type xchr int8 type xint int type xdob float64 type xflt float32 You want to copy the bytes (memory representation) of a value of the following struct type: type VEH1 struct { // 52 bytes total p xint // 4 bytes (READ BELOW) lat_lon_ele...

decltype does not resolve nested vectors. How can I use templates for nested vectors?

c++,templates,vector,nested

My other answer on here explains why your approach failed and one possible approach for a solution. I just thought of a much, much simpler one that I thought was worth sharing. The problem is that you can't use a trailing return type because the function name itself isn't in...

Global scope for array of structs inside function - Swift

arrays,function,swift,struct,shuffle

"...that doesn`t seem to work..." is a variation on perhaps the least helpful thing you can say when asking for help. What do you mean it "doesn't seem to work"?!?!? How doesn't it work? Explain what it's doing that doesn't meet your needs. Is it crashing? Is the shuffledQuestions array...

How to calculate a random point inside a cube

math,vector,3d,cube

Generate the points in the straight position then apply the rotation (also check the origin of the coordinates).

create vector of objects on the stack ? (c++)

c++,vector,heap-memory

Yes, those objects still exist and you must delete them. Alternatively you could use std::vector<std::unique_ptr<myObject>> instead, so that your objects are deleted automatically. Or you could just not use dynamic allocation as it is more expensive and error-prone. Also note that you are misusing reserve. You either want to use...

C++ vector error C2036: 'int (*)[]' : unknown size

c++,templates,c++11,vector

Your problem comes from this line: unique_ptr<vector<int[]>> m_indices; You should use a stl container instead, in this case it could be a vector of vector Also, why would you need a unique_ptr in this case? vectors support move semantics and you could just have a vector<vector<int>> m_indices; An extra hint...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional

Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...

Vector : References to generic type Vector should be parameterized

jsp,generics,vector

I don't think so these warnings would hang your IDE, these are harmless. And also it is always a best practice to specify the type for generics like Vectar<Object> or Vectar<String> or List<String> or ArrayList<String> etc and not use raw types. Please read from updated sources and books. It is...

C: Make generic iteration function?

c,arrays,struct,iteration

It's possible, but the proposed API isn't very nice. You're going to have to put iteration state somewhere, and you're not leaving any room for that. I would propose something like: struct DgIter { struct Dg *dg; size_t index; size_t dataSet; }; Then you can have functions like: struct DgIter...

How do I load data from a txt file into variables in my C program?

c,arrays,parsing,file-io,struct

I won't be writing the code, but can try to help with the algotihm, in general. Open the file. Help : fopen() Check for successful opening. Hint: Return value. Read a line from the file. Check for the success. Help : fgets() and Return value. Based on data pattern ,...

Vectorize thinking

r,vector,vectorization

I think you can try this, Thanks for @JacobH comment, this will be faster. x <- c(0,0,1,0,1,1,0) zeros <- which(x > 0) x[zeros[1]:tail(zeros, n = 1)] the output [1] 1 0 1 1 ...

Add same value multiple times to std::vector (repeat)

c++,vector,std

It really depends what you want to do. Make a vector of length 5, filled with ones: std::vector<int> vec(5, 1); Grow a vector by 5 and fill it with ones: std::vector<int> vec; // ... vec.insert(vec.end(), 5, 1); Or resize it (if you know the initial size): std::vector<int> vec(0); vec.resize(5, 1);...

GLFW3 create window returns null

c,opengl,struct,code-separation

The reason for not getting the window opened is that one has to specify GLFW_CONTEXT_VERSION_MINOR in addition to the other window hints. This could be done, e.g., with: glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); ...

Scoping rules for struct variables in GCC

c,gcc,struct,clang,scoping

As others mentioned, you're reading an uninitialized local variable and that's undefined. So, anything is legit. Having said that, there is a particular reason for this behavior: gcc reuses variables on the stack as much as it can (i.e., as long as the generated code is provably correct). You can...

Golang switch between structs

struct,go,interface,switch-statement

In your example you are trying to pass the struct itself to the function rather than an instance of the struct. When I ran your code it wouldn't compile. I agree with the comments above though, this would be much better handled by making sure each struct satisfies the fmt.Stringer...

VexCL vector of structs?

c++,struct,opencl

VexCL does not support operations with vectors of structs out of the box. You will need to help it a bit. First, you need to tell VexCL how to spell the type name of the struct. Let's say you have the following struct defined on the host side: struct point2d...

How can I pass a struct to a kernel in JCuda

java,struct,cuda,jni,jcuda

(The author of JCuda here (not "JCUDA", please)) As mentioned in the forum post linked from the comment: It is not impossible to use structs in CUDA kernels and fill them from JCuda side. It is just very complicated, and rarely beneficial. For the reason of why it is rarely...

Stuck on Structs(c++)

c++,function,struct

You have declared coordinate startPt, endPt; in main() and you are trying to access them Readcoordinate(). To resolve error you should declarecoordinate startPt, endPt;inReadcoordinate()` or pass them as argument. coordinate Readcoordinate() { coordinate startPt; cout << "Enter Longitude(in degrees)" << endl; cin >> startPt.latitude >> startPt.longitude >> startPt.city; return startPt;...

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector

The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...

Convert Vector to String?

java,vector

go for this, String name = String.valueOf(temp.get(0)); String value = String.valueOf(temp.get(1)); in case of Object.toString(), if the instance is null, a NullPointerException will be thrown, so, arguably, it's less safe.Whereas, using String.valueOf() you may not check for null. as ajb suggested you can handle ArrayIndexOutOfBoundsException by wrapping your code in...

How to pass pointer to struct to a function?

c,function,pointers,struct

Inside your doStuff() function, myCoords is already a pointer. You can simply pass that pointer itself to calculateCoords() and calculateMotorSpeeds() function. Also, with a function prototype like void calculateCoords(struct coords* myCoords) calling calculateCoords(&myCoords); from doStuff() is wrong, as it is passing struct coords**. Solution: Keep your function signature for calculateCoords()...

R Program Vector, record Column Percent

r,vector,percentage

Assuming that you want to get the rowSums of columns that have 'Windows' as column names, we subset the dataset ("sep1") using grep. Then get the rowSums(Sub1), divide by the rowSums of all the numeric columns (sep1[4:7]), multiply by 100, and assign the results to a new column ("newCol") Sub1...

Passing a struct to a template with extern const. What is the extern for?

c++,templates,struct,const,extern

This is one of the parts of the standard that changed from C++03 to C++11. In C++03, [temp.arg.nontype] reads: A template-argument for a non-type, non-template template-parameter shall be one of: [...] [...] the address of an object or function with external linkage, including function templates and function template-ids but excluding...

Who should clear a vector retrieved by reference?

c++,vector,pass-by-reference

In you first example the function is called "getVector" which is appropriate to describe what the function does. It returns a vector with a certain number of elements, as expected. In the second example the same does not apply. The function is still called "getVector" but now you want to...

Debug error: Vector iterator not dereferencable and Vector subscript out of range [closed]

c++,vector,stl,iterator

Just need to add after if (!found) { break; } that else { found = false; } If it is equal relationship.size() that means that no one item has been found. Anyway, found was not updated to false after each for loop, so if it find just one time an...

Defining a “vector_cast” template function that works with a variable amount of nested vectors

c++,vector,casting,nested

With vector type detection you might do: #include <iostream> #include <vector> // is_vector // ========= namespace Detail { template<typename T> struct is_vector_test { static constexpr bool value = false; }; template<typename ... Types> struct is_vector_test<std::vector<Types...>> { static constexpr bool value = true; }; } template<typename T> struct is_vector : Detail::is_vector_test<typename...

Adding elements to Struct Array

c,arrays,multidimensional-array,struct

Each currentGeneration is a pointer to a Generation. Yet when you declare an array Generation generations[MAX_GENERATIONS] it expects each index to be a Generation, not a pointer to one. But when you declare the array as Generation *generations[MAX_GENERATIONS] it expects each index to be a pointer to a Generation, which...

How to store large arrays of structs - Swift

arrays,swift,struct

The two ways to store the questions on disk are: 1) Core data 2) Sqlite I would suggest the following architecture to retrieve the stored questions: 1) Store 250 questions in core data/sqlite with each question associated with a number 1-250. 2) When you need to select 50 questions randomly,...

how to sort this vector including pairs

c++,vector

You forgot the return statement in the function bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { i.second.first < j.second.first ; } Write instead bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { return i.second.first < j.second.first ; } Also you should include header <utility> where class std::pair...

TypeError: zip argument #1 must support iteration (Vector sum for Ipython)

python,vector,ipython,linear-algebra,ipython-notebook

If you do vector_sum(a) the local variable result will be the integer "1" in your first step which is not iterable. So I guess you simply should call your function vector_sum like vector_sum([a,b,a]) to sum up multiple vectors. Latter gives [4,7,10] on my machine. If you want to sum up...

How to override C compiler aligning word-sized variable in struct to word boundary

c,gcc,struct,bit-packing

What you are looking for is the packed attribute. This will force gcc to not do any padding around members. Taken from the GCC Online docs: packed This attribute, attached to an enum, struct, or union type definition, specified that the minimum required memory be used to represent the type....

Add a matrix of 2x2 into a vector in c++

c++,matrix,vector

You cannot push back a matrix into a vector. What you can do is preallocate memory for your vector (for speeding things up) then use the std::vector<>::assign member function to "copy" from the matrix into the vector: vector<int> collectionSum(gray.rows * gray.cols); // reserve memory, faster collectionSum.assign(*auxMat, *auxMat + gray.rows *...

program failed. sharedPtr vector c++

c++,vector

The error location is 0x00000044, which usually means that this was NULL in the method call, while it is trying to access a member variable (at location this+0x44 in this case). Check that you are not calling addArtist() on a NULL Company* pointer....

Why I cannot use “fgets” to read a string to an element of my Struct?

c,pointers,memory-management,struct,fgets

Problems that I see: You are allocating the wrong amount of memory in the line: vet = (CLIENTES*)malloc(num*sizeof(int)); That should be: vet = malloc(num*sizeof(*vet)); See Do I cast the result of malloc?. The answers explain why you should not cast the return value of malloc. You are using fgets after...

Reordering vector of vectors based on input vector

c++,c++11,vector,stl,idioms

If you transpose the data, it's as easy as sorting the vectors by the index of the first element in them. This will be slower than your solution but may be more readable: void fix_order(std::vector<std::vector<std::string>>& data, const std::vector<std::string>& correct) { // setup index map, e.g. "first" --> 0 std::unordered_map<std::string, size_t>...

Cannot Properly Print Contents of Vector

c++,arrays,string,vector,segmentation-fault

You said: I have some C++ code where I'm taking input from a user, adding it to a vector splitting the string by delimiter, and for debugging purposes, printing the vector's contents. And your code does: while (true) { //Prints current working directory cout<<cCurrentPath<<": "; /// /// This line of...

Is it bad (or even dangerous) to random_shuffle vector of shared_ptrs?

c++,vector,shared-ptr,smart-pointers,shuffle

No, there is nothing bad or inefficient in this. std::random_shuffle only swaps the elements of the cointainer in some random way. std::swap is specialized for std::shared_ptr's, so it is safe and as efficient as swapping two pairs of raw pointers, without lots of reference counts could be going up and...

vector::push_back ( A * ) creating leaks?

c++,vector,push-back

If you do not have virtual destructor in your Node class, deleting your Directory objects through base class pointer is undefined behaviour. Your Directory class' s destructor won't be called, also the destructor of the contained vector. This might cause the memory leak.

OpenLayers 3: simple LineString example

javascript,vector,openlayers,openlayers-3

Just change this: var points = [ new ol.geom.Point([78.65, -32.65]), new ol.geom.Point([-98.65, 12.65]) ]; To: var points = [ [78.65, -32.65], [-98.65, 12.65] ]; The ol.geom.LineString constructor accept an array of coordinates....

sorting vector of pointers by two parameters

c++,sorting,vector

(b->y < a->y - offset) || (b->y > a->y + offset) These are two different cases, which should have different results. I suppose that b is "less" then a in first case, and "greater" in the other case, but your code returns false for both cases. See @Jonathan's answer on...

Referencing yourself inside of a struct

struct,go

You can't refer to a value inside its own declaration. You need to initialize the value first, then you can assign the method you want to use to Handler. testAuth := &Authorization{ Username: "someusername", Password: "somepassword", } testAuth.Handler = testAuth.HandleFunc auths := Authorizations{ "test": testAuth, } ...

How can I generate all the possible combinations of a vector

r,vector

Try combn(v1, 2, FUN=function(x) paste(rev(x), collapse="-")) #[1] "B-A" "C-A" "D-A" "E-A" "C-B" "D-B" "E-B" "D-C" "E-C" "E-D" If you want in the default order combn(v1, 2, FUN=paste, collapse="-") #[1] "A-B" "A-C" "A-D" "A-E" "B-C" "B-D" "B-E" "C-D" "C-E" "D-E" Update For a faster option, you can use combnPrim from grBase....

reinterpret_cast vector of derived class to vector of base class

c++,vector,c++03

To answer the question from your code : No, it's actually a very bad practice , and it will lead to undefined behavior. If sizeof(A) is equal to sizeof(B) your code might end up working ,considering that all functions derived in B and used inside f3 are virtual and non...

Swift Array Issues

ios,arrays,swift,struct,enums

You are using == rather than = for assigning let posState = positionState(pos) if posState != .None { if posState == .Off { boardArray[pos.row][pos.column] = .On } else { boardArray[pos.row][pos.column] = .Off } } ...

Have an if statement look ONLY at the first word in a string [duplicate]

c++,string,if-statement,vector

The first line places string beginning with 'abc' at the end, and the second erases them from the vector. auto end_it = std::remove_if(myvec.begin(), myvec.end(), [](const string &str){ return str.find("abc") == 0 ;}) ; myvec.erase(end_it, myvec.end()) ; ...

Sending vector data in the bus

vector,simulink,bus

The main idea is to create Bus of type you need. I did it this way: num = zeros(15,15,15); move = zeros(15,15,15); a = struct('number',num,'movement', move); busInfo = Simulink.Bus.createObject(a); You can see it's possible to create any data structure, array, vector anything you want and then create Bus Signal of...