c++ find_first_of

    find_first_of 函数原型如下:

 ForwardIterator1 find_first_of ( ForwardIterator1 first1, ForwardIterator1 last1,
                                    ForwardIterator2 first2, ForwardIterator2 last2 );
它从第一个范围里面寻找任何一个是第二个范围里的一个元素,返回第一次匹配的迭代器。如果找不到,返回第一个范围的最后一个迭代器。

从两个list中输出匹配的次数:
#include<iostream>
#include<list>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;


int main()
{
    string a="1234";
    const string b="1234";
    cout<<(a==b)<<endl;
    //list<string> firstList;
    list< string> firstList;//可以 list<const string>
    //list<string> secondList;
    vector< const char*> secondList; 
    string str;
    size_t count=0;
    typedef list< string>::iterator Iter;
    Iter it;
    cout<<"请输入第一个list"<<endl;
    while(cin>>str)
    {
        firstList.push_back(str);
    }
    cin.clear();
    cin.sync();
    cout<<"请输入第二个list"<<endl;
    while(cin>>str)
    {
        secondList.push_back(str.c_str());
    }

    cout<<*firstList.begin();
    it=firstList.begin();
 
    while((it=find_first_of(it,firstList.end(),secondList.begin(),secondList.end()))!=firstList.end())
    {
        ++count;
        ++it;
    }
    cout<<"found "<<count
        <<"names on both list"<<endl;
}

  str.c_str()  放回的是一个 const char* 类型,不能直接赋值给char*,所以第二个secondList必须是:

vector< const  char*> secondList; 

而不能是 vector< char*> secondList; 

 否则编译错误。

下面的程序有问题:

int main()
{
    char *c;
    string s="1234";
    c=s.c_str();
    cout<<c;
}
    

“=”: 无法从“const char *”转换为“char *”

可以改成:

 const char *c;
    string s="1234";
    c=s.c_str();
    cout<<c;

还可以strcpy(c,s.c_str);

若改成这样:

const char c[20];
    string s="1234";
    c=s.c_str();
   
    cout<<c;

报错:

“c”: 如果不是外部的,则必须初始化常量对象

“=”: 无法从“const char *”转换为“const char [20]”

 如果一个函数要求char*参数,可以使用c_str()方法:

 string s = "Hello World!";
 printf("%s", s.c_str()); //输出 "Hello World!"

 

原文地址:https://www.cnblogs.com/youxin/p/2510583.html