在C++中打印多个矢量的第一个值

Printing the first value from more than one vector in C++

本文关键字:第一个 C++ 打印      更新时间:2023-10-16

我正试图从下面主函数中显示的每个向量中打印第一个值

#include <iomanip>
#include <map>
using namespace std;
typedef unsigned int vect;
int main() {
std::vector<vect> p;
vector<vect> a = { 4,2,3,1 };
vector<vect> b = { 4,2,3,1 };
vector<vect> c = { 4,2,3,1 };
vector<vect> d = { 4,2,3,1 };
int i;
for (i=0; i<a.size(); i++)
cout << a[i];
}

函数first_preference((来自下方显示的函数.cpp

#include "function.h"
#include <string>
#include <iostream>
using namespace std;
person test::first_preference() const {
const person& first = p.front();
return first; //current first pref
}

该函数在这个头类中声明

#ifndef FUNCTION_H
#define FUCNTION_H
#include <vector>
typedef unsigned int person;
typedef unsigned int vect;
std::vector<vect> p;

class test {
public:
person first_preference() const;
};
#endif

我想从函数应该打印每个向量的第一个值的main((调用函数first_preference((,我该如何处理?

我希望从main()调用函数first_preference(),函数应该打印每个向量的第一个值

一些问题:

  • 您的头文件中有一个全局std::vector<vect> p(这不是一个好主意(,它被main中的std::vector<vect> p遮蔽。在main中放入p的内容将无法从test的实例访问。这些实例只知道全局CCD_ 9。

  • main.cpp中没有#include "function.h",因此无法在main中创建test对象。

  • 如果您在main.cpp#include "function.h",则不需要typedef unsigned int vect;,因为您已经在function.h中这样做了。这不是一个错误,而是令人困惑和不必要的。

  • vector<vect>实例a, b, cdtest或任何p都没有任何连接,因此除非以某种方式将它们传递给test,否则您在这些向量中输入的内容不可能由test的实例打印。

  • 您声明了vect的向量,但first_preference()按值返回personvectperson恰好是相同基本类型的别名,但这个接口似乎有问题。

  • main.cpp中,您不实例化test,而是对a进行迭代,并且从未调用过first_preference(),因此没有希望使用它。

  • 为什么"使用命名空间std;"被认为是不好的做法?