在容器中慎用指针。

现在我有一个数组需要传递,而且这个数组是在函数中计算得到的,程序中已经是使用了容器的传递方式,那么是使用std::vector<int*>还是std::vector<std::vector<int>>呢?

目前我是使用std::vector<std::vector<int>>可以正常传递,std::vector<int*>传递会有问题(下面代码自己调试)

如果有大佬看到,能够正确高效传递std::vector<int*>,请指正

#include <iostream>
#include <string>
#include <vector>

void fun1(std::vector<std::vector<int>>& vec)
{
	int a[3] = { 14, 87, 158 };
	std::vector<int> temp(a, a + 3);//这个初始化很关键
	vec.push_back(temp);
	return;
}

void fun2(std::vector<int*>& vec)
{
	int a[3] = { 14, 87, 158 };
	vec.push_back(a);
	return;
}

int main()
{
	std::vector<std::vector<int>> vec1;
	fun1(vec1);
	int a_1 = vec1[0][0];
	int a_2 = vec1[0][1];
	int a_3 = vec1[0][2];

	std::vector<int*> vec2;
	fun2(vec2);
	int b_1 = vec2[0][0];
	int b_2 = vec2[0][1];
	int b_3 = vec2[0][2];

	return 0;
}

20231216新增

#include <iostream>
#include <string>
#include <vector>

int main()
{
	using namespace std;
	
	//test1 -- good,没问题
#if 1
	{
		vector<string> strVec;
		for (int i = 0; i <= 10; ++i)
		{
			string str = to_string(i * i);
			strVec.emplace_back(str);
		}

		for (int i = 0; i < int(strVec.size()); ++i)
		{
			cout << strVec[i] << endl;
		}
		cout << endl;
	}
#endif
	
	//test2 -- bad,这种写法有问题
#if 1
	{
		vector<char*> sVec;
		for (int i = 0; i <= 10; ++i)
		{
			string str = to_string(i * i);
			sVec.emplace_back((char*)str.c_str());
		}

		for (int i = 0; i < int(sVec.size()); ++i)
		{
			cout << sVec[i] << endl;
		}
		cout << endl; }
#endif

	//test3 -- good,没问题
#if 1
	{
		vector<char*> sVec;
		for (int i = 0; i <= 10; ++i)
		{
			string str = to_string(i * i);
			char* c = new char[str.length() + 1];//+1是因为C语言中'\0'是字符串结束标志,不计入串长,但要占内存空间
			strcpy(c, str.c_str());
			sVec.emplace_back(c);
		}

		for (int i = 0; i < int(sVec.size()); ++i)
		{
			cout << sVec[i] << endl;
			delete[] sVec[i];//记住释放
		}
		cout << endl;
	}
#endif

	//csdn中应该这样写
#if 1
	{
		vector<int*> vec2;
		int* p = new int[3];
		p[0] = 123;
		p[1] = 159;
		p[2] = 147;

		vec2.emplace_back(p);
		cout << vec2[0][0] << endl;
		cout << vec2[0][1] << endl;
		cout << vec2[0][2] << endl;

		delete[] p;//记住释放
		cout << endl;
	}
#endif

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值