簡體   English   中英

如何根據 C++ 中的向量內容使用 std::move 移動元素?

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

我想知道是否可以根據向量中的內容將元素移動到另一個向量。 例如,我有一個三個向量。 點數,Player1 和 Player1type。 點向量中有整數,player1type 中有字符串,player1 應該有來自點向量的數字。


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;
} 

正如您在上面的代碼中所見,它只是通過替換 player1 中已有的元素來將點中的元素移動到 player1。 如果 player1type 中沒有任何 Steal 元素,我想要移動的元素。 所以它會是這樣的:

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

Player1 = {1,3,5};

我試圖實現這一點,但我無法讓它工作。

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;

} 

這似乎不起作用,它所做的只是添加數字而不管語句如何。

使用points.begin(), points.end()為整個向量移動元素。

對於您的條件情況,如果player1type!="Steal"您應該移動並相應地設置開始和結束移動點,您可以在循環中實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM