在向量中搜索其第一个参数的所有实例,然后在向量中返回这些实例

Searching a vector for all instances of its first argument, then returning those in a vector

本文关键字:实例 向量 然后 返回 搜索 第一个 参数      更新时间:2023-10-16

这确实是一个作业,但我被卡住了,这可能只是我没有得到的措辞。

创建一个具有可变参数数的函数,该函数在其余参数中搜索作为第一个参数提供的子字符串。此函数将返回一个向量,其中包含包含子字符串的所有参数

这是我到目前为止所拥有的:

#include <iostream>
#include <string>
#include <algorithm>
#include <stdarg.h>
#include <vector>
using namespace std;
vector<string> search(string str, ...);
int main (){
    va_list arguments;
    char contin = 'y';
    string str;
    va_start(arguments, str);
    cout << "Enter a string that will be searched for in the rest of the strings: ";
    str += va_arg(arguments, str);
    while(contin == 'y'){
        cout << "Enter a string that will be searched in: ";
        str += va_arg(arguments, str);
        cout << endl << "Enter ''y'' to continue or ''n'' to end to start seach:" << endl;
        cin >> contin;
    }
    va_end(arguments);
    search(arguments);
  return 0;
}
vector<string> search(string str, ... ){
    va_list containing;
    va_start (containing, str);
    if (std::find(str.begin(), str.end(), str.front()) != str.end()){
        str += va_arg(containing, str);
    }
    return containing;
}

我收到这些错误:第 37 行:"str += va_arg(包含,str(;" -错误 C2059:语法错误:"(">

第 40 行:"返回包含;" - 错误 C2664: 'std::vector<_Ty>::vector(const std::vector<_Ty> &(' : 无法将参数 1 从 'va_list' 转换为 'const std::vector<_Ty> &'

第 36 行:"if (std::find(str.begin((, str.end((, str.front((( != str.end((({" - 错误 C2039: 'front' : 不是 'std::basic_string<_Elem,_Traits,_Ax>' 的成员

第 21/24 行:"str += va_arg(参数,str(;" - 错误 C2059:语法错误:"(">

另外,我是否朝着正确的方向前进或做错了什么?

对于带有变量参数的函数,肯定有一些你不了解的地方。

首先,要使用变量参数调用函数,您只需使用常规方法

search("here", "are", "some", "strings");

其次,由于变量 arg 函数的参数类型未知,因此您可以调用该函数的值类型受到严重限制。禁止使用任何像std::string这样的复杂对象。简单的类型,如intdoublechar *都可以。

第三,va_arg宏的第二个参数是您希望访问的值的类型,例如 va_arg(containing, char*) .

我只能认为您的同义词中的"字符串"是指老式的 C 类型,即 const char *不是std::string.