我正在尝试使用以下代码处理两个字符串。结果很好但每当我尝试对第二个字符串执行相同的操作时,第一个字符串将被第二个字符串写入。例如,如果第一个字符串=“fuhg”,第二个字符串等于=“abc”,则第一个字符串变为:“abcg”。它可能与内存分配或类似的东西有关,但我无法弄明白,因为我在这方面不是很好。
string newPassChar;
string newBloom=bloomFilter(newPass);
int index=0;
for ( int k =0 ; k < alpha.length() ; k++ )
{
if (newBloom[k]=='1')
{
newPassChar[index]=alpha[k];
index++;
}
}
来自cppreference std::basic_string::operator[]:
No bounds checking is performed. If pos > size(), the behavior is undefined.
来自cppreference std::basic_string construcor:
1) Default constructor. Constructs empty string (zero size and unspecified capacity).
所以:
string newPassChar;
使用size() == 0
创建新字符串。
然后:
newPassChar[0] = ...
将覆盖字符串中的空字符。但是在下一次迭代中,当index = 1
,然后:
newPassChar[1] = ....
这是undefined behavior。并产生恶魔。
我想你在阅读时想要“推回”字符:
newPassChar.push_back(alpha[k]);
不需要存储用于索引字符串的另一个“索引”变量,字符串对象本身就知道它的大小,它可以在size()
方法中使用。