C++ 查找并替换数组的特定元素
我试图在数组中找到“empty”Bob,然后在找到empty在索引中的位置后,我想用“LEEROY JENKINS”替换“empty”一词,请原谅我的知识不足,我对此仍然很陌生,并尽我所能学习 问题:C++ 查找并替换数组的特定元素,c++,arrays,string,while-loop,C++,Arrays,String,While Loop,我试图在数组中找到“empty”Bob,然后在找到empty在索引中的位置后,我想用“LEEROY JENKINS”替换“empty”一词,请原谅我的知识不足,我对此仍然很陌生,并尽我所能学习 问题: int spindex()未找到正确的索引 空的没有被替换 #包括 #包括 使用名称空间std; int spindex(字符串x[],int n) { int i=0; int-tindex; while(x[i]!=“空”和&i
#包括
#包括
使用名称空间std;
int spindex(字符串x[],int n)
{
int i=0;
int-tindex;
while(x[i]!=“空”和&i cout问题在于构建循环的方式:
while (x[i] != "empty" && i < n)
{
tindex = i;
i++;
}
()
在我看来,整个问题最好是这样构造的:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string Bob[] = { "shaun", "empty", "tom", "empty", "chris", "sharon", "empty"};
auto it = std::find(std::begin(Bob), std::end(Bob), "empty");
if (it == std::end(Bob)) {
// No "empty" to replace!
return EXIT_FAILURE;
}
// Replace first "empty" with "BOB"
*it = "BOB";
// Here is our array now
std::cout << '[';
for (const auto el : Bob)
std::cout << el << ',';
std::cout << ']' << '\n';
}
// Output: [shaun,BOB,tom,empty,chris,sharon,empty,]
#包括
#包括)此函数
int spindex(string x[], int n)
{
int i = 0;
int tindex;
while (x[i] != "empty" && i < n)
{
tindex = i;
i++;
}
return tindex;
}
就这样说吧
size_t Q = spindex( Bob, sizeof( Bob ) / sizeof( *Bob ) );
编写函数的更通用方法如下所示
size_t spindex( const std::string a[], size_t n )
{
size_t i = 0;
while ( i < n && a[i] != "empty" ) i++;
return i;
}
size_t spindex( const std::string a[], size_t n, const std::string &s )
{
size_t i = 0;
while ( i < n && a[i] != s ) i++;
return i;
}
作为一种替代方法,您可以使用标准算法std::find
在标题
中声明的pim
值错误。为什么?使其变短了?忘记更改该值,但不更改结果只是一个小的未命中类型如果没有“空”,结果将显著更改在你的输入中。你能建议我如何解决这个问题吗?@ChronicArrow:我已经这样做了。我用语言说了,并提供了一个到现场演示的链接。作为奖励,我现在还提供了一个全新的解决方案。非常感谢你,我的垃圾互联网没有让我跟上你所说的内容!我的apologies@ChronicArrow:不客气,别客气或向上投票并接受!:)
size_t Q = spindex( Bob, sizeof( Bob ) / sizeof( *Bob ) );
size_t spindex( const std::string a[], size_t n, const std::string &s )
{
size_t i = 0;
while ( i < n && a[i] != s ) i++;
return i;
}
size_t Q = spindex( Bob, sizeof( Bob ) / sizeof( *Bob ), "empty" );