emplace_back和push_back() 函数添加 cv::Point 类型数据

emplace_back 和 push_back 是 C++ 中 std::vector用于添加元素的两个成员函数。

区别:

‌push_back‌:接受一个‌已构造好的对象‌(通过拷贝或移动),将其添加到容器末尾。

‌emplace_back‌:‌直接在容器内部构造对象‌,避免额外的拷贝或移动操作。

复制代码
#pragma once
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <fstream>
#include <vector> 



using namespace cv;
using namespace std;

int main()
{	

    vector <cv::Point>  rectpoint;
	vector <cv::Point>  rect;
    // 1.emplace_back写入数据:
	for (int i = 0; i < 9; i++)
	{
		if (i == 0)
		{
			rectpoint.emplace_back(1, 2);
		}
		if (i == 2)
		{
			rectpoint.emplace_back(3, 4);
		}
		if (i == 6)
		{
			rectpoint.emplace_back(5, 6);
		}
		if (i == 8)
		{
			rectpoint.emplace_back(7, 8);
		}
	}
    
    // 2.push_back写入数据:
    for (int i = 0; i < 9; i++)
	{
		if (i == 0)
		{
			
			// 方法1:push_back
			cv::Point p(1, 2);
			rect.push_back(p);
			// 方法2:rect.push_back(cv::Point(1, 2));
		}
		if (i == 2)
		{
			rect.push_back(cv::Point(3, 4));
		}
		if (i == 6)
		{

			rect.push_back(cv::Point(5, 6));
		}
		if (i == 8)
		{
			rect.push_back(cv::Point(7, 8));
		}
	}

    // 3.打印数据rectpoint:
	for (int i = 0; i < 4; i++)
	{
      cout << "rectpoint[i].x=" << rectpoint[i].x << ",rectpoint[i].y=" << rectpoint[i].y << endl;    ;
		 
	}
    // 4.打印数据rect:
	for (int i = 0; i < 4; i++)
	{
		cout << "rect[i].x=" << rect[i].x << ",rect[i].y=" << rect[i].y << endl; ;

	}


    // 5.修改-打印数据:
    rect[0].x = 313.760223;
	rect[0].y = 110.513077;
	rect[1].x = 422.942902; 
	rect[1].y = 112.106293;

	printf("1.rect_point_dilate=%f  rect_point_dilate=%f\n",
		int(rect[0].x), int(rect[0].y));
	printf("2.rect_point_dilate=%d  rect_point_dilate=%d\n",
		int(rect[0].x), int(rect[0].y));

    return 0;
}

打印结果:

rectpoint[i].x=1,rectpoint[i].y=2

rectpoint[i].x=3,rectpoint[i].y=4

rectpoint[i].x=5,rectpoint[i].y=6

rectpoint[i].x=7,rectpoint[i].y=8

rect[i].x=1,rect[i].y=2

rect[i].x=3,rect[i].y=4

rect[i].x=5,rect[i].y=6

rect[i].x=7,rect[i].y=8

1.rect_point_dilate=0.000000 rect_point_dilate=0.000000

2.rect_point_dilate=313 rect_point_dilate=110

相关推荐
样例过了就是过了2 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
橙子也要努力变强3 小时前
信号的保存、阻塞与递达
linux·服务器·c++
旖-旎3 小时前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
T0uken3 小时前
基于 vcpkg 与 LLVM-MinGW 的 Qt6 静态链接开发方案
c++·windows·qt
睡一觉就好了。3 小时前
C++11(一)
c++
水云桐程序员4 小时前
C++的主要应用场景
c++·学习方法
叼烟扛炮5 小时前
C++第一讲:C++ 入门基础
开发语言·c++·函数重载·引用·内联函数·nullptr
zh_xuan5 小时前
使用libcurl调用http接口
c++·github·libcurl