简体   繁体   English

打印单词列表(向量<string> ) 使用指针</string>

[英]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:我尝试了以下方法:

  1. I get an error when I tried using "*query_list_ptr" to dereference it at the "cout <<" line.当我尝试使用“*query_list_ptr”在“cout <<”行取消引用它时出现错误。
  2. I also get an error when I tried variations of "vector<string>* query_list_ptr" to "vector<string*> query_list_ptr".当我尝试“vector<string>* query_list_ptr”到“vector<string*> query_list_ptr”的变体时,我也遇到了错误。
  3. Another error is "query_list_ptr = query_list" that's why I ended up adding the ampersand to "query_list_ptr = &query_list;".另一个错误是“query_list_ptr = query_list”,这就是我最终将与符号添加到“query_list_ptr = &query_list;”的原因。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM