测试我的c++;在Xcode中编码,使用;Ab cde Fg";作为测试字符串,我的代码返回;“不是唯一的”;。。。为什么?代码如下所示 我在XC++中用C++进行面试问题,但是遇到了意外的行为,没有编译错误。代码将返回字符串是否包含所有唯一的ASCII字符。在Mac上用Xcode测试代码时,字符串“Ab cde Fg”返回“Not Unique”。为什么会这样 bool isUnique1(std::string str) { if (str.length() > 128) return false; bool * barr = new bool[128]; for (int i = 0; i < str.length(); i++) { int val = str[i]; if (barr[val]) return false; barr[val] = true; } delete[] barr; return true; } int main() { std::string name; bool result1; std::cout << "Enter a string to test: "; getline (std::cin, name); result1 = isUnique1(name); if (result1) std::cout << "Unique \n"; else std::cout << "Not Unique \n"; return 0; } bool isUnique1(std::string str) { 如果(str.length()>128) 返回false; bool*barr=新bool[128]; 对于(int i=0;i
数组未初始化。写入测试我的c++;在Xcode中编码,使用;Ab cde Fg";作为测试字符串,我的代码返回;“不是唯一的”;。。。为什么?代码如下所示 我在XC++中用C++进行面试问题,但是遇到了意外的行为,没有编译错误。代码将返回字符串是否包含所有唯一的ASCII字符。在Mac上用Xcode测试代码时,字符串“Ab cde Fg”返回“Not Unique”。为什么会这样 bool isUnique1(std::string str) { if (str.length() > 128) return false; bool * barr = new bool[128]; for (int i = 0; i < str.length(); i++) { int val = str[i]; if (barr[val]) return false; barr[val] = true; } delete[] barr; return true; } int main() { std::string name; bool result1; std::cout << "Enter a string to test: "; getline (std::cin, name); result1 = isUnique1(name); if (result1) std::cout << "Unique \n"; else std::cout << "Not Unique \n"; return 0; } bool isUnique1(std::string str) { 如果(str.length()>128) 返回false; bool*barr=新bool[128]; 对于(int i=0;i,c++,xcode,unique,getline,C++,Xcode,Unique,Getline,数组未初始化。写入 bool * barr = new bool[128](); 注意这根绳子 "Ab cde Fg" ^ ^ 包含非唯一空格 也许你应该这样写函数,它会忽略空白 如果要忽略空白,则可以使用下面的演示程序中所示的方法定义函数 #include <iostream> #include <iomanip> #include <string> #include <set> #include <cctype> b
bool * barr = new bool[128]();
注意这根绳子
"Ab cde Fg"
^ ^
包含非唯一空格
也许你应该这样写函数,它会忽略空白
如果要忽略空白,则可以使用下面的演示程序中所示的方法定义函数
#include <iostream>
#include <iomanip>
#include <string>
#include <set>
#include <cctype>
bool isUnique1( const std::string &s )
{
std::set<char> set;
std::pair<std::set<char>::iterator, bool> p( std::set<char>::iterator(), true );
for ( std::string::size_type i = 0; p.second && i < s.size(); i++ )
{
if ( not std::isspace( ( unsigned char )s[i] ) ) p = set.insert( s[i] );
}
return p.second;
}
int main()
{
std::cout << std::boolalpha << isUnique1( "Ab cde Fg" ) << '\n';
return 0;
}
否则,如果不能忽略空格,则循环将如下所示
for ( std::string::size_type i = 0; p.second && i < s.size(); i++ )
{
p = set.insert( s[i] );
}
谢谢你的帮助!我也曾经因为失望而失明,因为我看不到双空格的角色。
for ( std::string::size_type i = 0; p.second && i < s.size(); i++ )
{
p = set.insert( s[i] );
}
#include <iostream>
#include <iomanip>
#include <string>
#include <set>
#include <iterator>
#include <cctype>
bool isUnique1( const std::string &s )
{
return std::set<char>( std::begin( s ), std::end( s ) ).size() == s.size();
}
int main()
{
const char *s = "abcdefghijklmnopqrstuvwxyz";
std::cout << std::boolalpha << isUnique1( s ) << '\n';
return 0;
}
true