[英]To print a list of words (vector<string>) using pointers
I am trying to print the list of words from a vector of string (query_list) but I can't get it to work.我正在尝试从字符串向量 (query_list) 打印单词列表,但我无法让它工作。 I know that the current code prints the address.我知道当前代码会打印地址。
vector<string>* query_list_ptr;
query_list_ptr = &query_list;
for (i = 0; i < num_words; i++) {
cout << query_list_ptr << " ";
query_list_ptr++;
}
I tried the following:我尝试了以下方法:
Thanks for all the help.感谢所有的帮助。 I could do without pointers but it's for my CS class about pointers.我可以不用指针,但它适用于我的 CS class 关于指针。
The pointer to the first element of std::vector
can be obtained via the data()
member function.指向std::vector
的第一个元素的指针可以通过data()
成员 function 获得。
const string* query_list_ptr; // you want to print words, so I guess the pointer should point to string
query_list_ptr = query_list.data(); // get the pointer to the first element
for (i = 0; i < num_words; i++) {
cout << *query_list_ptr << " "; // dereference the pointer to get the word to print
query_list_ptr++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.