# Unity VS2010 problem with multiple declaration in for loop

This topic is 1831 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ehh... I'm pretty sure I'm doing this right.

I just got a new hard drive so I took the opportunity to upgrade to Win7 and VS2010 (since I can get them free through my school).

I'm trying to update some code with the C++x00 stuff in VS2010 and I came across this for loop that uses an 'erase' on an iterator. That rules out using for-each, but I noticed that I have the variables declared outside the loop and I want to bring them in. (I had put them outside before because they made the line way too long, but with 'auto' and the zooming feature it's managable now.)

Anyway, I tried putting the declaration of both the start and end iterators in the for(), but I got a compile error.

Is this thing busted (again)? I've subbed in simple int's and I stil have the same problem:
void VirtualKey::unbind(const Binding& binding) {
auto iter = m_bindings.begin();
auto end = m_bindings.end();
for(int i = 1, int j = 7; iter != end; ++iter) {
if((iter->device == binding.device) && (iter->diKey == binding.diKey)) {
iter = m_bindings.erase(iter);
if(iter == end) {break;}
}
}
}

I'm getting:
1>ClCompile:
1>  cl_VirtualKey.cpp
1>c:\users\khatharr\desktop\khatengine\khatengine\cl_virtualkey.cpp(22): error C2062: type 'int' unexpected
1>c:\users\khatharr\desktop\khatengine\khatengine\cl_virtualkey.cpp(22): error C2143: syntax error : missing ';' before ')'
1>c:\users\khatharr\desktop\khatengine\khatengine\cl_virtualkey.cpp(22): error C2143: syntax error : missing ';' before ')'
1>c:\users\khatharr\desktop\khatengine\khatengine\cl_virtualkey.cpp(22): error C2143: syntax error : missing ';' before '{'
1>c:\users\khatharr\desktop\khatengine\khatengine\cl_virtualkey.cpp(25): error C2043: illegal break
1>
1>Build FAILED.

Edit - Nevermind, I'm an idiot. You have to chain multiple declarations off the same type statement, so it would have to be:
int i = 1, j = 7;

Which should work for the auto's as well in this case. Edited by Khatharr

##### Share on other sites

You still have the problem of increasing your iterator twice when you erase an object.

Common ways are either if/else (if -> erase, else -> increment) or erasing a tmp iterator (auto tmp = iter++).

##### Share on other sites

You could always use the Std lib Algorithm's to side step the mistakes

m_bindings.erase(std::remove_if(std::begin(m_bindings), std::end(m_bindings),
[&binding](Binding &b) { return (b.device == binding.device) && (b.diKey == binding.diKey); })
, std::end(m_bindings));

?

##### Share on other sites
You still have the problem of increasing your iterator twice when you erase an object.

Common ways are either if/else (if -> erase, else -> increment) or erasing a tmp iterator (auto tmp = iter++).

Ah, derp. So it'd have to be:

void VirtualKey::unbind(const Binding& binding) {
for(auto iter = m_bindings.begin(), end = m_bindings.end(); iter != end; ) {
if((iter->device == binding.device) && (iter->diKey == binding.diKey)) {
iter = m_bindings.erase(iter);
}
else {
++iter;
}
}
}


So I still can't nice-looking syntax with erase. -.-

You could always use the Std lib Algorithm's to side step the mistakes

m_bindings.erase(std::remove_if(std::begin(m_bindings), std::end(m_bindings), [&binding](Binding &b) { return (b.device == binding.device) && (b.diKey == binding.diKey); })
, std::end(m_bindings));

Can't bring myself to do it.

##### Share on other sites
Can't bring myself to do it.

Why?

This code is basically self documenting and much easier to read.

##### Share on other sites

Nesting braces within parenthesis makes my eyes water. It's just one of those things I'm weird about.

I appreciate that algorithm syntax is better than it used to be, but I still just don't like it. (I'll eventually end up doing it, but I probably just need time to adapt. It took me quite a while with C++ before I started using STL.)

##### Share on other sites

Bear in mind that when you do erase it removes the element from the vector and then moves every element behind it up one place. If your vector is of any kind of size this rearranging of memory will be a lot slower then the STL way, which moves all the elements to be erased to the end of the vector and then erases everything at the end.

##### Share on other sites

When it is packed into one line it can get very dense. If you separate it out it becomes a bit more reasonable:

template<typename Container, typename Predicate> void remove_and_erase_if(Container &continer, Predicate predicate) {     auto begin = std::begin(container);     auto end = std::end(container);     auto i = std::remove_if(begin, end, predicate);     container.erase(i, end); }   auto predicate = [&binding](Binding &b) {     return (b.device == binding.device) && (b.diKey == binding.diKey); } remove_and_erase_if(bindings, predicate);

In particular, that helper function can be reused wherever.

Consider "swap and pop", if the order is irrelevant and erasing from the middle of the container is expensive.

##### Share on other sites
If you swap and pop is an option, then you might also consider std::partition() with erase() as well.

##### Share on other sites

I'll look into it more. I never thought of partition() for this, but I guess it's similar to remove_if().

I'm sort of surprised that there's not already an STL algorithm for the remove_if+erase combo. Seems like something that would come up pretty often.

Unbinds aren't performance critical and a single VitualKey should (should, lol) only have a handful of bindings at most, but I ought to practice a better strategy for this.

Thanks, all.

Edited by Khatharr

• 10
• 11
• 9
• 11
• 9
• ### Similar Content

• So I am building a turn based rogue-like (think CDDA). The game is going to have a very large map (up to 1000's x 1000's) however to alleviate most of that I obviously can't render everything so there will just be render a certain radius around the player and just load in and out data as the player moves.
The next major system I am prototyping is making interactive tiles destructible and pretty much everything will be destructible besides basic landscape (cars, doors, windows, structures, etc. will be destructible)
While I am only rendering a certain amount of tiles around the player, I want to keep the amount of colliders active at one time to be as small as possible for performance and currently the tilemap tool I use automatically merges colliders together.
So instead of creating a separate colliders for each of these tiles and having the destructible behavior tied to that object (which my tilemap tool would allow me to do) I was thinking that I would store an array of all the X and Y locations for the interactive tilemap layer and let the tilemap manage the colliders.
Then when I hit a collider on the interactive tilemap layer, instead of of getting the behavior for how to deal with the destruction for that tile from that game object, I would pull it from the array I mentioned earlier based on the tile I attempt to interact with which I already have.
Does this sound like a good approach? Any other recommendations would be welcomed.

• Hey guys,
I have a really weird problem. I'm trying to get some data from a REST service. I'm using the following code:

private void GetTheScores() { UnityWebRequest GetCommand = UnityWebRequest.Get(url); UnityWebRequestAsyncOperation operation = GetCommand.SendWebRequest(); if (!operation.webRequest.isNetworkError) { ResultsContainer rez = JsonUtility.FromJson<ResultsContainer>(operation.webRequest.downloadHandler.text); Debug.Log("Text: " + operation.webRequest.downloadHandler.text); } } The problem is that when I'm in Unity's editor, the request doesn't return anything (operation.webRequest.downloadHandler.text is empty, the Debug.Log command just prints "Text: "), but when I enter the debug mode and insert a breakpoint on that line, then it returns the text properly. Does anyone have an idea why is this happening?
The real problem I'm trying to solve is that when I receive the text, I can't get the data from the JSON. The markup is really simple:
[{"id":1,"name":"Player1"},{"id":2,"name":"Player2"}] and I have an object that should accept that data:
[System.Serializable] public class ResultScript { public int id; public string name; } There is also a class that should accept the array of these objects (which the JSON is returning):
[System.Serializable] public class ResultsContainer { public ResultScript[] results; } But when I run the code (in the debug mode, to get any result) I get an error: ArgumentException: JSON must represent an object type. I've googled it but none of the proposed solutions work for me.
Also (regardless if I'm in the debug mode or not) when I try to do some string operations like removing or adding characters to the GET result, the functions return an empty string as a result
Can you help me with any of these problems?
Thank you
• By nihitori
The Emotional Music Vol. I pack focuses on beautiful and esoteric orchestral music, capable of creating truly emotive and intimate moods. It features detailed chamber strings, cello and piano as the main instruments, resulting in a subtle and elegant sound never before heard in video game royalty-free music assets.

The pack includes 5 original tracks, as well as a total of 47 loops based on these tracks (long loops for simple use and short loops for custom / complex music layering).

A 15 seconds preview of each main track is available on Soundcloud:

• Another one of our new UI for #screenshotsaturday. This is the inventory screen for showing what animal fossils you have collected so far. #gamedev #indiedev #sama

• We're looking for programmers for our project.
Our project is being made in Unity
Requirements:
-Skills in Unity
-C#
-Javascript
-Node.js
We're looking for programmers who can perform a variety of functions on our project.
Project is a top-down hack-and-slash pvp dungeon-crawler like game. Game is entirely multiplayer based, using randomized dungeons, and a unique combat system with emphasis on gameplay.
We have a GDD to work off of, and a Lead Programmer you would work under.
Assignments may include:
-Creating new scripts of varying degrees specific to the project (mostly server-side, but sometimes client-side)
-Assembling already created monsters/characters with existing or non-existing code.
-Creating VFX
This project is unpaid, but with royalties.

---