将动态的指针宣布为字符串的问题
Problem with declaring a dynamic array of pointers to strings
在线执行练习作业时,我遇到了一个我无法解决的问题。
用户必须有一个数量(他将输入的句子数(,然后继续输入句子,将其存储为字符串(顺便说一句,宣布一系列动态的指针数组是强制性的(。但是,由于句子的数量不是先验的可推论,所以我知道指针数组的大小实际上是句子的数量,但是我不知道如何将一系列动态的指针声明为字符串。
使用我事先已经知道的东西,我想出了如何做相同的操作,但使用字符数组而不是字符串。将动态的指针宣布为动态的字符阵列的线看起来像这样:
char **ptr=new char*[n] {};
因此,在我的理解下,这会创建一个指针ptr
,该指针指向一个动态的指针数组,每个点的元素都指向一个字符数组。我现在想做类似的事情,结果应该是 ptr
是一个指向动态阵列的指针,每个点指向字符串的元素。
有人可以帮忙吗?我会感谢!
我认为您正在寻找的是
std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin >> num;
std::string *sentences = new std::string[num];
for(std::size_t i=0; i!=num; ++i) {
std::cout << "enter the " << (i+1) << "th sentencen";
std::cin >> sentences[i];
}
/*
... (do something with the sentences, accessing them as sentences[i])
*/
delete[] sentences; // free the memory
请注意,这种编码样式是高度灰心的。问题是需要管理分配的内存:避免记忆泄漏和悬空指针(包括例外安全(。正确的方法是使用容器或智能指针。例如:
std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin >> num;
std::vector<std::string> sentences{num};
for(std::size_t i=0; i!=num; ++i) {
std::cout << "enter the " << (i+1) << "th sentencen";
std::cin >> sentences[i];
}
/*
... (do something with the sentences, accessing them as sentences[i])
*/
或
std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin >> num;
std::unique_ptr<std::string[]> sentences{new std::string[num]};
for(std::size_t i=0; i!=num; ++i) {
std::cout << "enter the " << (i+1) << "th sentencen";
std::cin >> sentences[i];
}
/*
... (do something with the sentences, accessing them as sentences[i])
*/
在两种情况下,您都不必担心调用delete
:分配的内存将自动删除(即使发生异常(。
您可以完全避免使用
std::vector<std::string> input;
std::array
需要在编译时知道大小,并且您在运行时学习了这一点。该向量的工作方式就像数组一样,但可以在运行时有 push_back
ed。
您可以使用n
声明指向一些字符串的指针:
std::string * pInputs = new std::string[n];
但是使用矢量更容易。每个pInput
将是字符串,就像std::vector
版本一样。
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题