假设我有一个空终止字符串 vector ,其中一些可能是空指针。我不知道这是否合法。这是一个学习练习。
示例代码
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;
}
}
请注意,即使我在位置 c_strings1[1]
处有一个 NULL, vector 的大小也是 3
问题。如何使用 std::vector<char>
重写此代码
当你压入一个空值时, vector 中到底存储了什么?
编辑
我的问题的第一部分已得到彻底回答,但第二部分没有。至少我不满意。我确实想查看 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;
}
最佳答案
您没有 vector
字符串——你有一个 vector
指向字符的指针。 NULL 是一个完全有效的字符指针,恰好不指向任何东西,因此它存储在 vector 中。
请注意,您实际存储的指针是指向 char 文字的指针。字符串不会被复制。
混合C++风格意义不大vector
使用 C 风格的 char 指针。这样做并不违法,但像这样混合范式通常会导致代码困惑和困惑。
而不是使用 vector<char*>
或 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');
}
}
关于c++ - 如何在 std::vector 中使用空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555820/