现在我有一个数组需要传递,而且这个数组是在函数中计算得到的,程序中已经是使用了容器的传递方式,那么是使用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;
}