假设我有一个空终止字符串向量,其中一些可能是空指针。我不知道这是否合法。这是一个学习练习。
示例代码
std::vector<char*> c_strings1;
char* p1 = "Stack Over Flow";
c_strings1.push_back(p1);
p1 = NULL; // I am puzzled you can do this and what exactly is stored at this memory location
c_strings1.push_back(p1);
p1 = "Answer";
c_strings1.push_back(p1);
for(std::vector<char*>::size_type i = 0; i < c_strings1.size(); ++i)
{
if( c_strings1[i] != 0 )
{
cout << c_strings1[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,即使我在位置c_strings1[1]
Question处有一个 NULL,向量的大小也是 3 。std::vector<char>
当您推送空值时,如何使用向量中到底存储了什么来
重写此代码?
编辑
我的问题的第一部分已得到彻底解答,但第二部分尚未得到解答。至少我不满意。我确实想看看vector<char>;的用法 不是一些嵌套变体或std::vector<std::string>那些熟悉的变体。所以这是我尝试过的(提示:它不起作用)
std::vector<char> c_strings2;
string s = "Stack Over Flow";
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
// char* p = NULL;
s = ""; // this is not really NULL, But would want a NULL here
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
s = "Answer";
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
const char *cs = &c_strings2[0];
while (cs <= &c_strings2[2])
{
std::cout << cs << "\n";
cs += std::strlen(cs) + 1;
}
Run Code Online (Sandbox Code Playgroud)
你没有一个vectorof 字符串——你有一个vectorof 指向字符的指针。NULL 是一个完全有效的字符指针,它恰好不指向任何东西,因此它存储在向量中。
请注意,您实际存储的指针是指向 char 文字的指针。字符串不会被复制。
vector将 C++ 风格与 C 风格的 char 指针混合起来没有多大意义。这样做并不违法,但是像这样混合范例通常会导致代码混乱和损坏。
为什么不使用 a 而不是使用 avector<char*>或 a呢?vector<char>vector<string>
根据您的编辑,您似乎想要做的是将多个字符串压平为一个vector<char>,并在每个压平的字符串之间使用 NULL 终止符。
这是实现此目的的简单方法:
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
// create a vector of strings...
typedef vector<string> Strings;
Strings c_strings;
c_strings.push_back("Stack Over Flow");
c_strings.push_back("");
c_strings.push_back("Answer");
/* Flatten the strings in to a vector of char, with
a NULL terminator between each string
So the vector will end up looking like this:
S t a c k _ O v e r _ F l o w \0 \0 A n s w e r \0
***********************************************************/
vector<char> chars;
for( Strings::const_iterator s = c_strings.begin(); s != c_strings.end(); ++s )
{
// append this string to the vector<char>
copy( s->begin(), s->end(), back_inserter(chars) );
// append a null-terminator
chars.push_back('\0');
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17497 次 |
| 最近记录: |