注册 登录
编程论坛 C++教室

C++STL中的search_n函数应用于结构体出现问题

yoghurtjia 发布于 2014-03-08 22:10, 378 次点击
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct student{
    int    no;
    string name;
};

int main()
{
    vector<student>coll;
    student test;
    test.no   = 200;
    test.name = "jia";
    coll.reserve(80);
    int n;
    cin >> n;
    coll.resize(n);
    for (int i = 0; i < n; ++i)
    {
        cin >> coll[i].no >> coll[i].name;
    }
    vector<student>::iterator pos;
    //pos = search_n(coll.begin(),coll.end(),3,coll[1]);  受挫与结构体,结构体怎么使用呢。  

    return 0;
}


以上是我自己写的stl中的search_n函数,search__n函数是用来寻找一段区间中连续的n个等于定值的位置,在整形数组中没有问题,在结构体中失效了,希望大家来探讨一下
1 回复
#2
rjsp2014-03-10 08:57
你总得告诉search_n,两个student怎样才算是相等呀? 我来举个例子吧
程序代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>

struct student {
    int    no;
    std::string name;

    student( int id, const char* nm ) : no(id), name(nm)
    {
    }
};

using namespace std;

bool student_comp_1( const student& a, const student& b ) // 如果 no 相同,就认为student相等
{
    return a.no == b.no;
}
bool student_comp_2( const student& a, const student& b ) // 如果 name 相同,就认为student相等
{
    return a.name == b.name;
}

int main()
{
    vector<student> coll;
    coll.reserve( 5 );
    coll.push_back( student(0,"a") );
    coll.push_back( student(0,"b") );
    coll.push_back( student(1,"b") );

    vector<student>::iterator itor1 = search_n( coll.begin(), coll.end(), 2, student(0,"x"), &student_comp_1 );
    assert( itor1 == coll.begin()+0 );

    vector<student>::iterator itor2 = search_n( coll.begin(), coll.end(), 2, student(0,"b"), &student_comp_2 );
    assert( itor2 == coll.begin()+1 );

    return 0;
}

1