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
164 views
in Technique[技术] by (71.8m points)

c++ - How to remove duplicates from a vector?

I am writing a program that reads a text file in the form below, imports the data into a vector and then does some calculations with it. At the moment, I am able to import my data in pairs, insert them into a vector and sort the vector.. However all my efforts have failed when it comes to actually removing the duplicates so I can use the vector for other purposes.

1     4
5     6
4     5
4     5
5     4
6     7
...

This is currently my relevant code right now. If I do vec1.size() on the vector above(only the 6 lines), the output should be 5. However, every text file i try, I get an output of 1, I don't understand why..

while( getline( fs1, instrng ) ) {

    istringstream s1(instrng);
    int a, b;
    s1 >> a >> b;
    pair<int,int> pair1 = make_pair(a,b);
    vec1.push_back( pair1 );

    sort( vec1.begin(), myvec1.end() );
            auto last = std::unique(vec1.begin(), vec1.end());
            vec1.erase(last, vec1.end());
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Seems like you want to use a set instead of a vector.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...