I have vector pairs of integers both on first and second position and the input is rather specific.
Firstly, I have i inputs that all go into the first spots of the vector, but afterwards comes the second array of inputs that's supposed to go to the second position.
However, what I'd like to do, is I have a condition that if I find an input of the second spot bigger than a certain value (mana, in my case the variable), I'd like to simply not put it into the vector pair, and remove the first element on that index from the first position and I'm having trouble figuring out how to code it.
Here's the part of that code:
vector<pair<int, int>>spellOne;
for (int i = 0; i < nSpellOne; i++)
{
scanf_s("%d", &input);
spellOne.back().first = input;
}
for (int i = 0; i < nSpellOne; i++)
{
scanf_s("%d", &input);
if (input > mana)
{
// removing the element on .first position at i index
}
else
{
spellOne.at(i).second = input;
}
}
Could anyone help me out on how to do that and if that's even possible, or should I switch to a different type of arrays? I also considered using maps, but that wasn't possible, since there's a high chance I get the same value twice in either first/second spot in the vector, hence I can't use any of them as a key.
I made an example, which should get you boosted to complete your task. In my example bellow I populate the vector and then erase the pairs that have a second value greater than a certain threshold (2 in this case).
Now you can use two variables to keep track of the loop that erases the elements, one to loop through the whole vector and one to keep track of the current index to be checked; if we remove v[3], then the next element v[4] is shifted (because we called erase()) in place of v[3], thus we should examine index 3 again!
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main()
{
vector< pair<int, int> > v;
int N = 5;
const int threshold = 2;
for(int i = 0; i < N; ++i)
v.push_back(make_pair(i, i));
int i = 0;
while(i < v.size())
if (v[i].second > threshold)
v.erase(v.begin() + i);
else
i++;
for(int i = 0; i < v.size(); ++i)
cout << "(" << v[i].first << ", " << v[i].second << ")\n";
cout << "Done" << endl;
}
Output:
(0, 0)
(1, 1)
(2, 2)
Done
Edit for your comment: You could try that:
int i = 0;
while(i < nSpellOne.size())
{
scanf_s("%d", &input);
if (input > mana)
nSpellOne.erase(nSpellOne.begin() + i);
else
i++;
}
PS - When writing efficient code, don't bother for whether std::cin or scanf() is faster, focus on your algorithm!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With