检查数组中的值是否已存在
check if value inside array already exists
我是C++的初学者。这是我上大学的第一年。我完全坚持了这一点。我必须制作一个接受输入 4 个字符串的程序,然后检查某个值是否已经存在,如果存在,则输出值存在,仅此而已,如果它们都是唯一的(所有 4 个字符串),则按升序输出它们。下面的代码有效,它已经按升序输出它们,但是如何在编写值之前找到值是否重复?
对不起我的坏英语家伙,我希望你明白我在这里想说什么
string name[4];
string temp;
for(int i=0;i<4;i++){
cout<<"Enter "<<i+1<<" string"<<endl;
getline(cin,name[i]);
}
for(int i=0;i<4;i++){
for(int j=i+1;j<4;j++){
if(name[i]>name[j]){
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0; i<4; i++){
cout<<name[i]<< " ";
}
您可以使用字符串比较在推送之前对其进行检查。这是如果你想检查字符串是否唯一,而不是如果你在每个字符串中有共享的单词(这稍微复杂一些。
string name[4];
string temp;
for(int i=0;i<4;i++)
{
cout<<"Enter "<<i+1<<" string"<<endl;
getline(cin,name[i]);
}
int failed = 0;
for(int i = 0;i<4;i++)
{
for(int j=0;j<i;j++)
{
// Check if the string is the same as any previous strings.
if (name[i].compare(name[j]) != 0)
{
failed = 1;
cout<<"String exists multiple times: "<<name[i];
}
}
}
// Check if there were any shared strings
if(failed==0)
{
for(int i=0; i<4; i++)
{
cout<<name[i]<< " ";
}
}
参考:http://www.cplusplus.com/reference/string/string/compare/
所以最好的方法是使用更好的容器!
让我们来看看这里的std::set
。
std::set 是一个关联容器,其中包含一组排序的 独特的对象。
那么我们如何才能最好地使用它,有很多例子,但我们可以看看你的特定例子。
#include <set> // For Set
int main() {
set<string> names; // our fun easy ordered set.
string name; // a name to read in
unsigned int nameCounter = 0; // a counter
// loop until we have 4 correct names.
while (nameCounter < 4) {
cout<<"Enter "<<nameCounter+1<<" name"<<endl;
getline(cin,name);
// Check that when they enter it into the set that it is actually inserted.
// Here we are being clever because "insert" returns a tuple with a bool
// to tell us if we put it in correctly.
if (!names.insert(name).second) {
cout << "That was not unique!" << endl;
} else {
nameCounter++;
}
}
// Now we can loop through the names which is already sorted for us!
for (auto listName : names) {
cout << listName << " ";
}
cout << endl;
}
这不是那么容易吗!?利用std
库几乎总是比自己做事更好!
这是一个活生生的例子。
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if((name[i]==name[j]) && (i!=j)){
cout<<"already exits";
}
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- std::weak_ptr 和相应的 std::shared_ptr 之间是否存在数据竞争?
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?