在我的代码中使用列表、成员函数和类是否正确
Is use of list, member functions, and classes correct in my code?
在用MATLAB编码后,我不得不回到C++。我错过了一些东西。无论如何,我写了一个代码来创建可扩展的人的名字、姓氏和年龄列表。通过可扩展,我的意思是,如果需要,以后可以创建更多条目。
它实例化了 5 人的名字、姓氏和年龄。我需要使其可扩展,并计算人员列表的平均年龄。我在代码中使用了列表。
#include <iostream>
#include <list>
int main() {
// Create a list of first names and initialize it with 5 first names
std::list<string> firstname(new string[] { "Brad", "John", "Neptune", "Kuh", "Dhar", "Rock" });
// Iterate over and display first names
for (string val : firstname)
std::cout << val << ",";
std::cout << std::endl;
// Create a list of last names and initialize it with 5 last names
std::list<string> lastname(new string[] { "Mish", "Jims", "Nepers", "Yho", "Har", "Ock" });
// Iterate over and display first names
for (string val2 : lastname)
std::cout << val2 << ",";
std::cout << std::endl;
// Create an empty list of ages pf persons
std::list<int> ages(5, {34, 56, 57, 91, 12});
// Iterate over the list and display ages
for (int val1 : ages)
std::cout << val1 << ",";
std::cout << std::endl;
// Compute average age
for (int jj=0; jj <5; jj++)
agesum = age(jj) + age(jj+1);
avage = agesum/(jj+1);
return 0;
}
但是,它不会执行,并给出错误。您能否更正代码,并就正在发生的事情向我提供反馈?
这就是你想要的吗?
#include <string>
#include <iostream>
#include <vector>
int main(){
std::vector<std::string> first_names {"Brad", "John", "Neptune", "Kuh", "Dhar", "Rock"};
std::vector<std::string> last_names {"Mish", "Jims", "Nepers", "Yho", "Har", "Ock"};
std::vector<int> ages {34, 56, 57, 91, 12};
int avg_age = 0;
for(int age : ages) avg_age += age;
avg_age /= ages.size();
if(first_names.size() == last_names.size()){
for(int i = 0; i < first_names.size(); i++){
std::cout << first_names[i] << " " << last_names[i] << "n";
}
}
std::cout << "average age: " << avg_age << "n";
}
相关文章:
- 函数是否可以访问传递给main()的参数
- 根据某个函数是否存在启用模板
- 无论如何,我可以确定构造函数是否存在吗?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何检查函数是否在LLVM Instrumentation pass的ModulePass的系统头文件中定义?
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 在对象构造期间,将指向尚未构造的子对象的指针传递给另一个子对象的构造函数是否危险?
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 由并发无序映射查找线程调用的函数是否安全?
- 使用静态成员函数而不是普通函数是否有任何开销?
- 从其存储的回调中删除 std::函数是否安全
- 析构函数是否会自动调用 delete[] C++?
- 构造函数是否有一种现代C++方法来了解其'container'类?
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- 移动构造函数是否C++过时?
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 此函数是否会在C++中创建内存泄漏?
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 如何检测构造函数是否与抛出的析构函数无关