简体   繁体   English

如何打印出char **向量的内容

[英]how to print out contents of char** vector

SO, 所以,

I am looking to print out the contents of a vector; 我正在寻找打印矢量的内容; I have tried an iterator for it but that is no good 我已经尝试了一个迭代器,但这不好

for(vector<char**>::const_iterator i=myVec.begin();i!=myVec.end();i++) {
   cout<<**i<<endl;
}

this does not work, what I am thinking is I will need two iterators (the above one will be the outer one, and the inner one would be as such: 这是行不通的,我在想的是,我需要两个迭代器(上面的一个是外部的,内部的是这样的:

  for(vector<char*>::const_iterator j=???;j!=??;j++) {....}

but I haven't been able to get it to work. 但我无法使其正常工作。

Thanks. 谢谢。

Seems to work just fine here: 似乎在这里可以正常工作:

#include <iostream>
#include <vector>

int main()
{
    const char* sentence1[] = {"foo", "bar", "baz"};
    const char* sentence2[] = {"xyzzy", "frob", "plugh"};
    std::vector<const char**> vec = {sentence1, sentence2};

    for (auto i : vec) {
        for (size_t w = 0; w < 3; ++w) {
            std::cout << i[w] << ' ';
        }
    }
    std::cout << '\n';
}

This will print: 这将打印:

foo bar baz xyzzy frob plugh

The above is C++11. 以上是C ++ 11。 If you don't have that, you'll need to change the vector initialization and the for loop: 如果没有,则需要更改向量初始化和for循环:

std::vector<const char**> vec;
vec.push_back(sentence1);
vec.push_back(sentence2);

for (std::vector<const char**>::iterator it = vec.begin();
     it != vec.end(); ++it)
{
    for (size_t w = 0; w < 3; ++w) {
        std::cout << (*it)[w] << ' ';
    }
}

As you can imagine, you'll need to assume the same amount of words for each sentence. 可以想象,每个句子需要假设相同数量的单词。 If you don't want that, you can create a new data structure that also holds the amount of words per sentence together with the vector of sentences. 如果您不希望这样做,则可以创建一个新的数据结构,该结构还保存每个句子的单词数量以及句子的向量。

Being a masochist is a good exercise, but for practical purposes you should probably switch to vectors so that you can iterate over the words more easily. 成为受虐狂是一个很好的练习,但是出于实际目的,您可能应该切换到向量,以便可以更轻松地遍历单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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