C++中在容器Vector中使用结构体Struct


简单介绍 具体请看 http://www.cnblogs.com/qyaizs/articles/2039101.html


#include <iostream>
#include <vector>
using namespace std ;
struct Rect
{
int Dir;
int Ini;
int Inj;
};
int main()
{
Rect rect;
vector<Rect>vec;

for (int i=0;i<10;i++)
{
rect.Dir=i;
rect.Ini=i+2;
rect.Inj=i*i;
vec.push_back(rect);
}
for (int i=0;i<vec.size();i++)
{
cout<<vec[i].Dir<<"\t"<<vec[i].Ini<<"\t"<<vec[i].Inj<<endl;
}

system("pause");
}


如果想做成全局的结构体容器的话 参考如下

//test.h
#ifndef _TEST_H
#define _TEST_H

#include <iostream>
#include <vector>

struct Student
{
	int age;
	int id;
};

class TEST
{
public:
	TEST(){};
	~TEST(){};
	void prrr();
};
class CVX_FEA
{
public:
	CVX_FEA();
	~CVX_FEA();
	void daoru();
    void pr();
	Student ZhiFei;
	std::vector<Student>Information;
	void pri();
	TEST* PENV;
};
#endif


//test.cpp
#include "test.h"
#include <iostream>
using namespace std ;
CVX_FEA::CVX_FEA()
{
	cout<<"构造函数"<<endl ;
}
CVX_FEA::~CVX_FEA()
{
	cout<<"析构函数"<<endl ;
}
void CVX_FEA::daoru()
{
	
	for (int i=0;i<10;i++)
	{
		ZhiFei.age=i+3;
		ZhiFei.id=i^2;
		Information.push_back(ZhiFei);
	}

}
void CVX_FEA::pr()
{
	daoru();
	for (int i=0;i<10;i++)
	{
		cout<<Information[i].age<<endl ;;
		cout<<Information[i].id<<endl ;
	}
	PENV->prrr();
}
void CVX_FEA::pri()
{
	cout<<"ghjk";
}
void TEST::prrr()
{
	cout<<"SDSFAF";
}
int main()
{
	
	CVX_FEA FEA;	
	FEA.pr();
	system("pause");

}




C++中,如果你有一个自定义结构体并且想要从`std::vector`中移除所有重复项,可以使用递归来遍历并检查每个元素是否已经存在于集合中。这里是一个简单的例子,假设你的结构体名为`MyStruct`: ```cpp #include <iostream> #include <vector> #include <unordered_set> // 自定义结构体 MyStruct struct MyStruct { // 假设这里有两个字段用于唯一标识 int field1; std::string field2; bool operator==(const MyStruct& other) const { return field1 == other.field1 && field2 == other.field2; } }; // 使用一个无序集合(Set)来存储已见的元素 std::unordered_set<MyStruct> seenElements; // 递归函数,接收vector和索引作为参数 void removeDuplicates(std::vector<MyStruct>& vec, size_t index = 0) { if (index >= vec.size()) { // 如果已到达末尾,结束递归 return; } // 检查当前元素是否已经在集合中 if (seenElements.find(vec[index]) != seenElements.end()) { // 如果存在,则删除并继续处理下一个 vec.erase(vec.begin() + index); return removeDuplicates(vec, index); // 递归调用,跳过已删除的位置 } else { // 如果不存在,添加到集合中然后进入下一层迭代 seenElements.insert(vec[index]); return removeDuplicates(vec, index + 1); } } int main() { std::vector<MyStruct> myVector = { /* ... */ }; // 填充你的向量 removeDuplicates(myVector); // 输出处理后的vector for (const auto& item : myVector) { std::cout << "Item: {" << item.field1 << ", " << item.field2 << "}\n"; } return 0; } ``` 在这个示例中,`removeDuplicates` 函数会通过递归地比较每个元素和之前见过的元素来移除重复。如果遇到重复,就从向量中删除该元素,并调整递归调用的索引来忽略已删除的元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值