2014-09-29 97 views
1

我知道如何從指定位置擦除C++矢量元素。假設我有向量A = [0 1 0 1 1 0 0 1]。我想刪除在4個位置的元素,位置存儲在矢量B = [1 4 7 8]。這我可以這樣做:刪除某些位置以外特定位置的元素

sort (B.begin(), B.end()); 
for(int i=B.size() - 1; i >= 0; i--){ 
     A.erase(A.begin() + B[i]); 
    } 

問題:我有向量C = [3 4] 。向量C的大小總是小於B的大小。現在我必須擦除A中的B.size()元素,如上面的代碼所示。這裏的條件是,如果B的任何索引與C的索引相同,則應該改變B的索引,使得B的索引都不與C相同。這意味着可以改變B的索引,但是可以改變B的索引應該是一樣的。對於這種情況,B的索引可以是B = [1 2 7 8]。現在B的索引不包含C的索引,我可以應用上面的代碼。

任何人都可以告訴我如何得到它?

+1

對於這種情況,B的索引可以B = [1 2 7 8]。 它們也可以是[1 5 7 8]或[1 6 7 8]。你如何決定? – CinCout 2014-09-29 08:46:00

+0

你也可以是別人,但索引不應該是C的索引,因爲那可能是我們可以使用rand()函數。 – Hum 2014-09-29 08:51:37

+0

所以你已經有一個公平的想法是什麼要求!爲什麼不在這裏尋求幫助之前先試一試呢? – CinCout 2014-09-29 08:52:38

回答

0

下面是一個嘗試:

#include <random>  // std::mt19937, std::uniform_int_distribution 
#include <algorithm> // std::set_difference, std::sort 
#include <vector>  // std::vector 

//Generate a random number called here rdmNb using <random> 
//std::mt19937 gen(seed); 
//std::uniform_int_distribution<int> rdmNb(0, A.size-1)); 

int main() 
{ 

//Data initialization (using C++11) 
std::vector<int> vA = {0, 1, 0, 1, 1, 0, 0, 1}; 
std::vector<int> vB = { 1, 2, 7, 8}; 
std::vector<int> vC = {3, 4}; 
int rdmNb=1; //just so it compiles (replace by the random generator function) 

//Code 
std::vector<int> vD(vB.size(),-1); 
std::vector<int>::iterator endIt; 

std::sort (vB.begin(), vB.end()); 
std::sort (vC.begin(), vC.end()); 

do { 
    endIt = std::set_difference (vB.begin(), vB.end(),vC.begin(), vC.end(), vD.begin()); 
    for (std::vector<int>::iterator it(endIt); it< vD.end(); it++) { 
     *it = rdmNb; 
     vB = vD; 
    } 
} while (*(dD.end()-1)==0); //while (endIt!=vD.end()); 

//Your normal code: 
for(int i=vD.size() - 1; i >= 0; i--){ 
    vA.erase(vA.begin() + vD[i]); 
} 

return 0; 
}