您好,我有一个学校项目,需要使用 C++ 创建索引系统。
我遇到了一个问题,我需要能够检查一个字符串是否与我创建的任何结构中的任何字符串完全相同,然后显示该结构中的所有信息。我已经找到了一种方法来处理一些值,随着声明更多的结构,这些值变得非常乏味。
#include <iostream>
using namespace std;
int main()
//create the structure
struct example{
string name;
int age; }
// declare two different struct variables
example 1;
1.name = "Hello World!";
1.age = 60;
example 2;
2.name = "Toothpaste";
2.age = 75;
// create another string
new_string = "Hello World!";
//this is were I have my problems with the if statement
if(new_string == 1.name){
cout << "Your string is named " << 1.name << " and is " << 1.age << "years old" << endl;
}
else if(new_string == 2.name){
cout << "Your string is named " << 2.name << " and is " << 2.age << "years old" << endl;
}
else{
break
}
这会创建大量我认为不必要的代码,我想知道如何创建一个系统,在该系统中我可以检查字符串是否等于任何内容,然后调用整个结构,而不需要 25 个不同的“else if”声明。考虑到我的结构也有更多的变量,尝试输入所有这些变量似乎是一座大山......
C++20 代码看起来像这样
using namespace std;
#include <vector>
#include <string>
#include <iostream>
#include <ranges>
struct example_t
{
std::string name;
int age;
};
// Output an example to a stream, makes later code more readable
// pass example_t by const, becuase it should not be modified
// pass by reference to avoid the struct to be copied
std::ostream& operator<<(std::ostream& os, const example_t& example)
{
os << "name = " << example.name << ", age = " << example.age;
return os;
}
auto ShowExampleByName(std::ranges::forward_range auto& range, const std::string& name_to_find)
{
// https://en.cppreference.com/w/cpp/algorithm/ranges/find
auto findByName = [&](const std::string name) { return name == name_to_find; };
auto it = std::ranges::find_if(range, findByName, &example_t::name);
if (it != range.end())
{
std::cout << "found : " << *it << "\n";
}
}
int main()
{
// in C++ if you need more than one thing of something
// use std::vector
std::vector<example_t> examples{ {"Alice",21}, {"Bob",33}, {"Charlie",12} };
// try to avoid index based for loops, so use a range based for loop
for (const auto& example : examples)
{
std::cout << example << "\n";
}
// and the reusable code matching your example
ShowExampleByName(examples,"Bob");
}