简体   繁体   English

如何将点添加到结构类型的向量

[英]How can I add points to a vector of a struct type

I am trying to add points(vertices) to a vector of struct type. 我试图将点(顶点)添加到结构类型的向量。 I am a beginner and I know I can use push_back. 我是一个初学者,我知道我可以使用push_back。 But I keep getting three errors: 但是我不断收到三个错误:

  • no appropriate default constructor available 没有合适的默认构造函数
  • left of '.push_back' must have class/struct/union “ .push_back”的左侧必须具有class / struct / union
  • expression must have class type. 表达式必须具有类类型。

What I am doing wrong? 我做错了什么? Here's my code... 这是我的代码...

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <math.h>
using namespace std;

struct Points
{
    int x, y;
    Points(int paramx, int paramy) : x(paramx), y(paramy) {}  
}p1,p2;

vector <Points> pointes();

void addPoint(int a, int b);
void directionPoint(Points p1, Points p2);

int main()
{
    return 0;
}

void addPoint(int x, int y)
{
    pointes.push_back(Points(x, y));    
}

void directionPoint(Points p1, Points p2)
{  
    if ((p1.x*p2.y - p2.x*p1.y) > 0)
    {
        cout << "direction is anticlockwise" << endl;
    }
    else
        cout << "direction is clockwise" << endl;
}

std::vector doesn't require its value type to be default-constructible. std::vector不需要其值类型是默认可构造的。 The reasons for compile errors are different: 编译错误的原因不同:

struct Points
{
  //...
}p1,p2;

You declare p1 and p2 with no arguments. 您声明不带参数的p1p2 To do that struct Points must have a default constructor. 为此, struct Points必须具有默认构造函数。 You have to either remove them or specify arguments for the constructor. 您必须删除它们或为构造函数指定参数。

Also, 也,

vector <Points> pointes();

This declares a function pointes taking no arguments and returning vector<Points> . 这声明了一个函数pointes它不带任何参数并返回vector<Points> Declare it just as vector <Points> pointes; 就像vector <Points> pointes;指出的那样声明它vector <Points> pointes;

After these two changes the code compiles: Demo 在这两个更改之后,代码将编译: Demo

The error no appropriate default constructor available is caused by your code 错误没有合适的默认构造函数是由您的代码引起的

} p1,p2;

This can be corrected by either creating an appropriate constructor in your struct, removing these values if not needed, or using the existing constructor: 可以通过在您的结构中创建适当的构造函数,如果不需要删除这些值或使用现有的构造函数来纠正此问题:

} p1(0,0),p2(0,0);

The left of '.push_back' must have class/struct/union and expression must have class type error is caused by “ .push_back”左侧必须具有class / struct / union,表达式必须具有类类型错误是由于

vector <Points> pointes();

To correct it remove the parenthesis: 要更正它,请删除括号:

vector <Points> pointes;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM