Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

c++ - Pick every element once from sorted array

I have a sorted array and I want to take every element once into an other array

Example:

Input:  array[] = { 1,2,2,3,3,5 }
Output: array2[] = { 1,2,3,5 }

Here is my attempt

int db = 0,array2[100];

for(int i = 0;i < k;i++){
    int j = 0;
    for(j = 0;j < db;j++){
        if(array[i] == array2[j]){
            break;
        }
    }
    if(i == j){
        array2[db] == array[i];
        db++;
    }
}
/* PRINT
for(int i = 0;i < db;i++){
    cout<<array2[i]<<" ";
}
cout<<endl;*/
question from:https://stackoverflow.com/questions/65854178/pick-every-element-once-from-sorted-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a standard algorithm std::unique_copy that does exactly this:

auto end = std::unique_copy(std::begin(array), std::end(array), array2);

The returned iterator end points to one past the last element that is inserted into array2, so you can calculate the number of unique elements that were copied like this:

auto num = std::distance(array2, end);

I would recommend using std::vector instead of arrays anyway, and then you don't have to worry about computing the number of copied unique elements. In case you use a vector the 3rd argument to the algorihtm would be std::back_inserter(vec).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...