简体   繁体   中英

How to move elements using std::move depeding on contents of vector in C++?

I would like to know if I can move elements to another vector depending what there is in the vector. So for example I have a three vectors. Points, Player1 and Player1type. The point vector has integers in it, the player1type has strings in it and the player1 is supposed to have numbers from the points vector.


int main() {

    vector <int> points {1,2,3,4,5};
    vector <string> player1type {"Power1", "Steal", "Power2", "Steal", "Power1"};
    vector <int> player1 {1,1,1,1,1};

    move(points.begin(), points.end(), player1.begin());


return 0;
} 

As you can see in the code above it simply moves the elements in points to player1 by replacing the elements that are already in player1. What I want is the elements to move if there aren't any Steal elements in player1type. So it would be like this:

player1type = {"Power1", "Steal", "Power2" ,"Steal", "Power1"};

Player1 = {1,3,5};

I have tried to implement this but I can't get it to work.

int main() {

    vector <int> points {1,2,3,4,5};
    vector <string> player1type {"Power1", "Steal", "Power2", "Steal", "Power1"};
    vector <int> player1 {1,1,1,1,1};

    if (!player1type.empty() && player1type[0] == "Power1") {


    move(points.begin(), points.end(), player1.begin());

    }

    else if (!player1type.empty() && player1type[0] == "Power2") {

        move(points.begin(), points.end(), player1.begin());

    }

    else {

        cout << "Can't apply this sorry" << endl;       

    }

return 0;

} 

This doesn't seem to work, all it does is adds in the numbers regardless of the statements.

Your moving elements for the whole vector using points.begin(), points.end() .

For your conditional situation you should move if player1type!="Steal" and set up start and end move points accordingly, which you can achieve in a loop:

vector <int> points {1,2,3,4,5};
vector <string> player1type {"Power1", "Steal", "Power2", "Steal", "Power1"};
vector <int> player1 {1,1,1,1,1};

for(int i=0; i<5; ++i)
{  if (!player1type.empty() && player1type[i] != "Steal") 
   move(points.begin()+i, points.begin()+i+1, player1.begin()+i);
   else player1[i]=0;
}
for(auto i:player1)
cout<<i; // 1 0 3 0 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM