在向量中搜索其第一个参数的所有实例,然后在向量中返回这些实例
Searching a vector for all instances of its first argument, then returning those in a vector
这确实是一个作业,但我被卡住了,这可能只是我没有得到的措辞。
创建一个具有可变参数数的函数,该函数在其余参数中搜索作为第一个参数提供的子字符串。此函数将返回一个向量,其中包含包含子字符串的所有参数
这是我到目前为止所拥有的:
#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
这样的复杂对象。简单的类型,如int
、double
和char *
都可以。
第三,va_arg
宏的第二个参数是您希望访问的值的类型,例如 va_arg(containing, char*)
.
我只能认为您的同义词中的"字符串"是指老式的 C 类型,即 const char *
不是std::string
.
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如何检查类实例向量的索引是否为空
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- 当函数返回C++向量实例时,它正在运行
- 为什么我不能更改实例化对象内部的向量?
- 在两个类实例之间共享向量
- 在使用标准向量函数时引发'std::bad_alloc'实例后调用的终止
- 从新实例的向量中检索数据返回 0
- 基类中向量的干净实例化
- 在向量中存储实例
- 类实例的C++/向量作为另一个类的属性
- 没有操作员=的类型向量的实例化
- 是否可以使用将不同参数传递给构造函数的类的不同实例初始化向量
- 向量映射作为实例成员的C 地图
- make_pair并push_back基指针,并实例化基指针的向量
- 尝试使用两个单独的 getline() 实例来填充两个单独的向量
- C -STD ::向量没有超载函数的实例
- 对成员变量的引用在向同一向量中添加另一个实例后断开
- (C++)用于实例化新对象并将其分配给指向相同对象类型的指针的 2D 向量的语法
- GDB监视实例向量中的类成员