我需要调整数组的大小并将值复制到那里...所以我知道,我需要一个动态数组,但我不能使用 vector
并且必须使用静态数组..我写了这样的东西:
string names1[0];
bool foo(const char * inFile1) {
int size = 0;
ifstream myfile(inFile1);
if (myfile.is_open()) {
// iterate through lines
while (getline(myfile, line)) {
string tmp[++size];
for (int i=0; i!=size;i++)
tmp[i]=names1[i];
names1=tmp;
names1[size]=line;
}
}
}
尽管如此,在线 names1=tmp;
我明白了
main.cpp:42:20: error: incompatible types in assignment of ‘std::string [(((unsigned int)(((int)(++ size)) + -0x000000001)) + 1)]’ to ‘std::string [0]’
...我是 C++ 的新手,作为一个 javaguy,我真的很困惑:-S 感谢您提供任何建议,如何解决这个问题..
最佳答案
变量 names1
是一个包含零个条目的数组(这本身就是一个问题),您尝试为该变量分配一个字符串。这将不起作用,因为字符串数组不等于字符串。
首先,我建议您使用 std::vector
而不是零大小的数组。
要继续,您不需要将一个字符一个字符地复制到一个临时变量中,只需将读取的字符串添加到 vector 中即可:
std::vector<std::string> names1;
// ...
while (std::getline(myfile, line))
names1.push_back(line);
如果您不能使用 std::vector
,那么您必须分配一个适当的数组,其中更多 个条目。如果超过该值,则必须重新分配它以增加数组的大小。
类似于:
size_t current_size = 1;
std::string* names1 = new std::string[current_size];
size_t line_counter = 0;
std::string line;
while (std::getline(myfile, line))
{
if (line_counter > current_size)
{
std::string* new_names1 = new std::string[current_size * 2];
std::copy(names1, names1 + current_size, new_names1);
delete[] names1;
names1 = new_names1;
current_size *= 2;
}
else
{
names1[line_counter++] = line;
}
}
关于C++ 动态数组 - 通过复制两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455118/