2012-04-07 61 views
0

我该如何在C++中做到这一点? 在巨蟒C++数组[从:到]

example = [u'one', u'two', u'three', u'four'] 
print example[1:3] 

我该怎么做,在C++(我缺少这个功能) 我需要改写这个以C++

while i<len(a)-1: 
       if (a[i]=='\x00' or a[i]=='\x04') and (eval("0x"+(a[i-1].encode("hex"))) in range(32-(4*eval((a[i].encode("hex")))),128-(12*eval((a[i].encode("hex")))))): 
        st+=a[i-1:i+1] 
        i+=2;continue 
       elif st=='': 
        i+=1;continue 
       elif len(st)>=4 and (a[i-1:i+1]=='\x00\x00' or a[i-1:i+1]=='\x0a\x00' or a[i-1:i+1]=='\x09\x00' or a[i-1:i+1]=='\x0d\x00'): 
        s.STRINGS.append([st.decode("utf-16le"),0xffffff]) 
        s.INDEX.append(iCodeOffset+i-1-len(st)) 
        st='' 
        i=i-1;continue 
       else: 
        st='' 
        i=i-1;continue 

我需要从二进制文件的字符串列表,而不使用字符串。 exe文件

THX为预先 Benecore

+0

既然你解决问题,以C++社区,请解释一下Python程序做什么和你有什么在转换成C++和面临的困难尝试。 – Mahesh 2012-04-07 12:37:04

回答

0

下面是一个返回一个新的拼接向量GI的函数然后老一个。它只做最基本的拼接(从:到),并且只在一个方向上(不确定from from是否大于,但我相信python会颠倒输出)。

template<typename T> 
std::vector<T> splice(const std::vector<T> in, int from, int to) 
{ 
    if (to < from) std::swap(to, from); 

    std::vector<T> ret(to - from + 1); 

    for (to -= from; to + 1; to--) 
    { 
     ret[to] = in[from + to]; 
    } 

    return ret; 
} 
0

首先,有在C++中对此没有立即更换,因为C++是不是蟒蛇,有自己的习惯用法工作方式不同。

首先,对于字符串,您可以使用特定std::string::substr

对于更通用的容器,您应该知道C++通常在对所述容器的元素进行操作时工作基于迭代器。例如,假设你想在矢量比较元素,你会做类似如下:

#include <iostream> 
#include <algorithm> 
#include <vector> 

int main() 
{ 
    std::vector<int> a = {1,2,3,4}; 
    std::vector<int> b = {1,2,10,4}; 
    std::cout << "Whole vectors equal? " << (std::equal(a.begin(), a.end(), b.begin())?"yes":"no") << std::endl; 
} 

现在,假设我们只需要前两个值(如[:2])比较,然后,我们将改写最后声明是这样的:

std::cout << "First 2 values equal? " << (std::equal(a.begin(), a.begin()+2, b.begin())?"yes":"no") << std::endl; 

假设我们要在最后两个值,我们会做比较:

std::cout << "Last 2 values equal? " << (std::equal(a.end()-2, a.end(), b.begin())?"yes":"no") << std::endl; 

看到这个模式出现? x.begin()+i,x.begin()+j大致等于[i:j],而x.end()-i,x.end()-j)大致等于[-i,-j]。请注意,你可以混合这些当然。

所以一般在处理容器时,你将使用一系列迭代器,这个迭代器的范围可以被指定为非常类似于python的列表拼接。它更冗长,它是另一个成语(拼接列表再次列表,但迭代器不是容器),但您会得到相同的结果。

最后的一些注意事项:

  • 我写x.begin()使代码更清楚一点,你也可以写std::begin(x),这是比较通用的,也适用于数组。 std::end
  • 看看the algorithms library,然后再编写自己的循环遍历迭代器。
  • 是的,你可以写自己的for循环(类似for(auto it = a.begin(); it != a.end(); it++),但往往更容易和更一致的函数或lambda传递给std::foreach
  • 真的记得C++没有Python或反之亦然。
+0

是的,我知道,C++是不是Python,但在Python我写的应用程序,我可以提取二进制文件/编辑字符串,但我的应用程序有12 MB,因为是写在wxPython中,所以我需要它改写为C++,但我能找到任何从二进制文件中提取字符串的例子。字符串列表。 – Benecore 2012-04-07 17:45:41

+0

@Benecore这是如何表达python的范围内运营商在C++ – KillianDS 2012-04-08 14:08:15

+0

是一个完全不同的问题,但我有脚本从二进制文件中提取字符串,我想改写它,但我不知道有可以重写阵列 – Benecore 2012-04-08 14:10:43