我绝对是C ++的新手,因为大学的教授正在教我C atm,但我只是自己学习C ++(实际上是试图混合C的速度和C ++的效用)。 这有点难......而且这是我无法确定的事情。
下面的代码是更大的程序的一部分,但我决定写这个小部分只是为了向你展示错误,它们发生的方式(这些都是它们,但更多......自程序以来更大)
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <stdio.h>
#include <numeric>
#include <string>
typedef struct stud
{
std::string name;
unsigned int fak_no;
struct b_date
{
int M;
int D;
unsigned Y;
};
std::string adm_gr;
std::vector <float> grades;
float sum_div_2;
};
void imp_data ( std::vector <stud> imp_vec ( int x ) )
{
printf ( " Import data for each person: \n " );
for ( std::vector <stud>::iterator it = imp_vec.begin(); it != imp_vec.end(); it++
{
std::cout << " for person " << ( it - imp_vec.begin() ) +1 << ": " << " \n";
std::cout << " names: ";
std::getline (std::cin, imp_vec.at (*it).name);
}
}
void main ()
{
int size;
printf ( " Number of persons: " );
std::cin >> size;
std::vector <stud> lads (size);
imp_data ( lads (size) );
system ( " pause " );
}
我通常得到的错误是:左边......实际上是什么 - &gt; .at()。bind()。end()不是类/结构/联合 - 但是怎么样?我认为向量至少是一个联合,不是说这个是struct类型。 第二.. std :: getline需要3个参数......我提供了2 ...哈哈? 第三,“术语不会在imp_data();
中评估为一个参数的函数”花了太多时间试图解决这个问题,但仍未成功。 如果有人能提供帮助,我将非常感激,这肯定会促进我的学习......
答案 0 :(得分:3)
std::vector <stud> imp_vec ( int x )
不是对象。 std::vector <stud> imp_vec
是。但对std::vector <stud> & imp_vec
你的代码中有很多类似的拼写错误。
还有一些你需要要做的事情,同时学习C ++编码:首先编写一小段代码并编译它们。然后,您可以轻松地修改语法错误和拼写错误代码,而不是一次性修改数百行代码。
因此,在撰写本文时,您应该从以下内容开始:
void imp_data ( std::vector <stud> imp_vec ( int x ) )
{
}
void main ()
{
int size = 20;
std::vector <stud> lads (size);
imp_data ( lads (size) );
}
然后修复其中的所有错误。然后添加更多代码并重复。
答案 1 :(得分:2)
您的代码中有几处改进:
无需混合printf()
和I / O流:std::cout
可以将字符串输出到控制台。
在C ++中struct Something
很好,不需要typedef struct Something
。
使用++it
(预增量)来增加迭代器(而不是it++
; it++
是过早的悲观化:)。
学习正确格式化代码,尤其是缩进。
不要包含不必要的标题。
请注意,在imp_data()
函数中,imp_vec
向量由函数填充,结果应传递给调用者,因此您应该将其传递给( const)参考:void imp_data(std::vector<stud>& imp_vec)
。
如果使用现代C ++(C ++ 11/14),则可以使用auto
(或基于范围的for
)进行循环迭代。至少使用auto
,您不必拼写长迭代器类型名称。
查看代码的潜在改进:
#include <iostream>
#include <string>
#include <vector>
struct stud {
std::string name;
// ... other fields ...
};
void imp_data(std::vector<stud>& imp_vec) {
std::cout << "Import data for each person:\n";
for (auto it = imp_vec.begin(); it != imp_vec.end(); ++it) {
std::cout << "for person " << ((it - imp_vec.begin()) + 1) << ": " << " \n";
std::cout << "name: ";
// std::cin >> it->name;
std::getline(std::cin, it->name);
}
}
int main() {
std::cout << "Number of persons: ";
int size;
std::cin >> size;
std::vector<stud> lads(size);
imp_data(lads);
// Output names
std::cout << "\nNames:\n";
for (const auto & x : lads) {
std::cout << x.name << std::endl;
}
}
享受您的学习过程。