使用旧的c++编译器查找字符串Vector的索引
Find Index of a string Vector using older compiler C++
我正在寻找在用户输入字符串后我正在使用的向量的索引。
我使用的向量是:
vector<string> names;
经过几个小时的研究,这就是我想到的,仍然不起作用,我使用的是旧的编译器DEV c++,使我无法使用distance + find()。
int find(vector<string>&v )
{
string t;
bool found=false;
for(int i=0; i< v.size(); i++)
{
cout << "Enter the string to find " << endl;
cin >> t;
if(v[i]==t)
{
found=true;
return i;
}
}
if(!found)
{
found=!true;
return -1;
}
}
您使用的逻辑不正确。在查看vector之前,需要先询问用户输入。
这个函数还可以稍微简化一下。
int find(vector<string>&v )
{
string t;
// Gather the input from the user first
cout << "Enter the string to find " << endl;
cin >> t;
// Now look for the string in the vector.
for(int i=0; i< v.size(); i++)
{
if(v[i]==t)
{
return i;
}
}
// If execution gets here, the string was not found.
return -1;
}
一个更好的函数设计是不要在函数中调用cin
。让用户在调用函数中收集他们想要搜索的字符串
int find(std::vector<std::string> const& v,
std::string const& t )
{
for(int i=0; i< v.size(); i++)
{
if(v[i]==t)
{
return i;
}
}
// If execution gets here, the string was not found.
return -1;
}
In main
:
int main()
{
// Construct v and flesh it out.
std::vector<std::string> v;
...
std::string t;
// Gather the input from the user first
cout << "Enter the string to find " << endl;
cin >> t;
int index = find(v, t);
...
}
看,如果你没有std::find
,一定要自己写。但至少要让它在某种程度上可重复使用。
- 不要一直要求用户输入。作为函数参数传递。
-
不要把
std::string
硬接进去。template<typename T> int find(std::vector<T> const&v, T const& e) { for(int i = 0; i < v.size(); ++i) if(v[i] == t) return i; return -1; }
您现在可以在string
, int
或任何真正实现operator==
的向量上使用find
实现。
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 有没有办法将字符串添加到 Vector 中,但前提是它尚不存在?->C++
- 连接和压缩标准::vector<std::字符串的最佳方法>
- C++ 无法将 std::vector<BYTE> 转换为字符串或字符数组
- 如何在C++中处理多维字符串 VECTOR 的字符?
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- "error: subscripted value is not an array, pointer, or vector",我正在使用字符串
- 从 vector<pair<string, int 中提取不包含 0 的字符串>>
- 如何确定字符串是否包含在 std::vector 的任何字符串中
- 检查一系列单词,形成一个文本文件,保存在字符串vector C 中
- 仅威胁唯一字符串 - 什么是更快的 vector<std::string> 或只是 std::string
- 检查 std::vector 中的字符串是否包含C++中的子字符串
- 如何将十六进制字符串分为std :: vector
- STD :: vector和std ::字符串重新分配策略
- C++ vector 中不存在的字符串成员变量
- cout错误地打印出字符串的Vector
- 无法将C风格的字符串推送到std::vector中
- std::vector中的字符串验证
- 将 vector<unsigned char> {1,2,3} 转换为字符串"1-2-3" AS DIGITS
- 使用旧的c++编译器查找字符串Vector的索引