注册 登录
编程论坛 C++教室

【编写程序定义一个 vector 对象,其每个元素都是指向 string 类型的指针,读取该 vector 对象,输出每个string 的内容及其相应的长度。】

zklhp 发布于 2014-01-31 01:55, 633 次点击
程序代码:

#include <iostream>
#include <vector>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;

int main(void)
{
    string str[] = {"1", "22", "333"};
    vector<string *> pstr_vec;
    for (size_t i = 0; i != len; ++i)
    {
        pstr_vec.push_back(str + i);
    }
    for (vector<string *>::iterator p = pstr_vec.begin(); p != pstr_vec.end(); ++p)
    {
        cout << **p << endl;
        cout << (**p).size() << endl;
    }
    return 0;
}


不知道这里初始化是否可以写的简单一些 还有就是这个写的怎么样啊 看书基本上闭门造车 希望能得到大神的指点

顺便说一点感慨 这些迭代器神马的 不就是lisp里面的mapc一类的么 例如emacs lisp

(mapc (lambda (x) (message "%d" x)) '(1 2 3))

遍历 对每个元素执行一个匿名函数 这里是输出 返回原来的list 我一直感觉差不多的东西 只不过用C++写就高大上了


[ 本帖最后由 zklhp 于 2014-1-31 02:01 编辑 ]
3 回复
#2
ml2325282014-03-14 16:02
如果不用指针的话可以用insert
vector<string> pstr_vec;
pstr_vec.insert(pstr_vec.begin(),str,str + sizeof(str)/sizeof(str[0]));
#3
rjsp2014-03-14 16:16
不会lisp,但C++可以这么搞
程序代码:
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    for( int e : {1,2,3} )
        cout << e << '\n';

    int s[] = { 1, 2, 3 };
    for_each( std::begin(s), std::end(s), [](int e){cout<<e<<'\n';} );

    return 0;
}

#4
zklhp2014-03-14 18:06
以下是引用rjsp在2014-3-14 16:16:47的发言:

不会lisp,但C++可以这么搞
#include  
#include  
using namespace std;
 
int main()
{
    for( int e : {1,2,3} )
        cout << e << '\n';
 
    int s[] = { 1, 2, 3 };
    for_each( std::begin(s), std::end(s), [](int e){cout<
我一定努力学习向您看齐
1